How can I change the labels of these buttons in DT::Datatable in R and change collors of rows?
Asked Answered
I

2

8

I need to change labels of Buttons DT::Datatable in R. Thanks for you help! DataTble

O DT:Datatable está com a extensão que permite alguns recursos de formatação, mas não documenta todos.

Ela usa a extensão Buttons para fitrar colunas na tabela. O botão "search" eu consegui mudar o atributo: language = list(search = 'Procurar:')

Queria saber se alguém já usou esse recurso no shiny e se poderia me ajudar.

ui.R

library(shiny)
library(readr)
library(memoise)
library(tm)
library(wordcloud)
library(DT)

tesesFO <<- read.csv("TesesFOResumoUnico.csv", colClasses = "character",stringsAsFactors = TRUE, sep = ";")


shinyUI(
  fluidPage
        (

  h1("TesesFO"),
          # Adiciona o CSS 
          tags$style(my_css),

    sidebarLayout(
      sidebarPanel(
        width = 3,
        title = "Entrada dados",
        hr(),
        sliderInput(inputId = "ano", label = "Intervalo de Tempo",
                    min = 2000, max = 2025, step = 2,
                    value = c(2010, 2018)),
        # Add an "All" value to the continent list
        selectInput("depto", "Departamento",
                    choices = c("Todos", tesesFO$Depto),
                    multiple = TRUE,
                    selectize = TRUE,
                    selected = 'Todos'),
        textAreaInput(inputId="texto1",
                      label ="Digite um texto",
                      value = "Texto para analise",
                      height = '200px',
                      width =  '250px'),
        hr(),
        actionButton("update", "Atualizar"),
        hr()




      ),

    mainPanel(
          tabsetPanel(

                tabPanel(
                  title = "Tabela de Teses",
                  br(),
                  DT::dataTableOutput("table"),
                  # Add a download button
                  downloadButton(outputId = "download_data", label = "Download")

                         ),

                tabPanel("Cloud",plotOutput("plot",width = "100%"), 

                         sliderInput("max", "Número máximo de palavras:",
                                     min = 1,  max = 300,  value = 20)    

                         )



          #Fecha tabsetPanel
    )
    ) #Fecha mainPanel   
    ) #Fecha Sidebarlayout
    ) #Fecha e fluidPage

) #Fecha shinyUI 

server.R

    library(shiny)



    shinyServer(function(input, output) {

      filtered_data <- reactive ({

        data <- tesesFO
        data <- subset(
          data,
          Ano >= input$ano[1] & Ano <= input$ano[2]
        )
        # Trata a Caixa 
        if (input$depto != "Todos"){
          data <- subset(
            data,
            Depto ==input$depto
          )
        }
        data
      })

      getTermMatrix <- memoise(function(book) {


        data <- tesesFO
        data <- subset(
          data,
          Ano >= input$ano[1] & Ano <= input$ano[2]
        )
        # Trata a Caixa 
        if (input$depto != "Todos"){
          data <- subset(
            data,
            Depto == input$depto
          )
        }
        data
        data <- data$ResumoBR

        # Separando somente os resumos
        resumosBR <- data

        #text <- readLines(sprintf("./%s.txt.gz", book),
        # encoding="UTF-8")

        myCorpus = Corpus(VectorSource(resumosBR))
        myCorpus = tm_map(myCorpus, content_transformer(tolower))
        myCorpus = tm_map(myCorpus, removePunctuation)
        myCorpus = tm_map(myCorpus, removeNumbers)
        myCorpus = tm_map(myCorpus, removeWords,
                          c(stopwords("SMART"), "a","a","à","ainda","além","ambas","ambos","antes","ao","aonde","aos","após","após"
 ))

        myDTM = TermDocumentMatrix(myCorpus,
                                   control = list(minWordLength = 1))

        m = as.matrix(myDTM)

        sort(rowSums(m), decreasing = TRUE)


      })

      # Make the wordcloud drawing predictable during a session
      wordcloud_rep <- repeatable(wordcloud)

      output$plot <- renderPlot({

        terms <- reactive({
          # Change when the "update" button is pressed...
          input$update

          data <- tesesFO
          data <- subset(
            data,
            Ano >= input$ano[1] & Ano <= input$ano[2]
          )
          # Trata a Caixa 
          if (input$depto != "Todos"){
            data <- subset(
              data,
              Depto %in% input$depto
            )
          }
          data

          # ...but not for anything else
          isolate({
            withProgress({
              setProgress(message = "Processing corpus...")
              getTermMatrix(data)

            })
          })
        })

         v <- terms()

        wordcloud_rep(names(v), v, scale=c(4,0.5),
                      min.freq = 1, max.words=input$max,

                      colors=brewer.pal(8, "Dark2"))
      })
      output$table <- DT::renderDataTable(
        {
        data <- filtered_data()

        DT::datatable(data = data, extensions = c('AutoFill','Buttons','FixedHeader'),
                      options = list(pageLength = 10,autoWidth = TRUE,targets = 5,
                                     language = list(search = 'Procurar:'),
                                     dom = 'Bfrtip',
                                     buttons = list(list(extend = 'colvis', columns = c(1:9)))),
                      style = 'default',
                      class = 'table-bordered table-condensed'
                      )
      })

      # Create a download handler
      output$download_data <- downloadHandler(
        filename = "teses_data.csv",
        content = function(file) {
          # The code for filtering the data is copied from the
          # renderTable() function
          data <- filtered_data()


          # Write the filtered data into a CSV file
          write.csv(data, file = "teses.csv", row.names = FALSE,col.names=TRUE, sep=",")
        }
      )

    })
Isomer answered 20/7, 2018 at 14:37 Comment(3)
If this is for shiny I'd add that tag to your question.Syncytium
Please add code for this datatableKubis
The button "Collumn Visibility" I did. DT::datatable(data = data, extensions = c('AutoFill','Buttons','FixedHeader'), options = list(pageLength = 10,autoWidth = TRUE,targets = 5, language = list(search = 'Procurar:'), dom = 'Bfrtip', buttons = list(list(extend = 'colvis', columns = c(1:9),text = 'Exibir/Ocultar Colunas'))), style = 'default', class = 'table-bordered table-condensed' )Avant
C
14
datatable(mtcars, 
          extensions = "Buttons", 
          options = list(dom="Bfrtip", 
                         buttons = list(list(extend = "colvis", 
                                             text = "Exibir/Ocultar Colunas")), 
                         language = list(paginate = 
                                           list('next'="MY_NEXT", 
                                                previous="MY_PREVIOUS"))))

enter image description here

Candis answered 20/7, 2018 at 17:54 Comment(0)
L
3

Two small addendums to @stéphane-laurent answer.

1) If you want to add more buttons, you need to create separate sub-lists for each of them. So for example:

datatable(
      mtcars, 
      extensions = "Buttons", 
      options = list(
          dom = "Bfrtip", 
          buttons = list(
              list(
                  extend = "colvis",
                  text = "Exhibir/Ocultar Columnas"
                  ),
              list(
                  extend = "copy",
                  text = "Copiar"
                  )
               )
            )
         )

would generate two buttons, one for coping with the name "Copiar" and one for column selection with the name "Exhibir/Ocultar Columnas". The order in which you add the sub-lists will determine the order in which the buttons populate, left-to-right.

2) You can change the language using the paginate option and cover every text instance in the widget. But you can also select a language using the language option as follows:

datatable(
      mtcars, 
      extensions = "Buttons", 
      options = list(
          options = list(
          language = list(
              url = 'https://cdn.datatables.net/plug-ins/1.10.11/i18n/Spanish.json'
              ),
          dom = "Bfrtip", 
          buttons = list(
              list(
                  extend = "colvis",
                  text = "Exhibir/Ocultar Columnas"
                  ),
              list(
                  extend = "copy",
                  text = "Copiar"
                  )
               )
            )
         )

I'm not sure which is the url for Portuguese, but I'm guessing just replace ".../Spanish.json" for ".../Portuguese.json". Oddly enough, this doesn't change the button labels, so you are going to have to do does manually.

Datatable documentation on this here.

Lingwood answered 29/12, 2019 at 21:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.