简体   繁体   中英

Get selected columns in DT table

I am developing a shiny app where user can select multiple columns in a big dataset to create a subset of this dataset. I use the package DT to render the table nicely in the shiny app.

I previously used version 0.2 of DT package where the following code was working :

library("DT")
library("shiny")

ui <- fluidPage(
  DT::dataTableOutput('table1'),
  DT::dataTableOutput("table2")
)

server <- function(input, output) {
  output$table1 <- DT::renderDataTable({
    datatable(mtcars, extensions = 'Select', selection = 'none', options = list(ordering = FALSE, searching = FALSE, pageLength = 25, select = list(style = 'os', items = 'column')),
              callback = JS(
                "table.on( 'click.dt', 'tbody td', function (e) {",
                "var type = table.select.items();",
                "var idx = table[type + 's']({selected: true}).indexes().toArray();",
                "var DT_id = table.table().container().parentNode.id;",
                "Shiny.onInputChange(DT_id + '_columns_selected', idx);",
                "})"
              ))
  })

  output$table2 <- DT::renderDataTable({
    subset_table <- mtcars[,input$table1_columns_selected]
    datatable(subset_table)
  })
}

shinyApp(ui = ui, server = server)

Unfortunately, this code is not working anymore (I am now under version 0.4). The input$table1_columns_selected does not render the indices of the selected columns. According to this https://rstudio.github.io/DT/shiny.html there is now a functionnality to select multiples rows, but I can't figure out how to do the same with columns.

Any idea ? Thank you very much for your help !

I am not sure why you need to use the callback argument to do this. Here's a simplified approach -

library("DT")
library("shiny")

ui <- fluidPage(
  DT::dataTableOutput('table1'),
  DT::dataTableOutput("table2")
)

server <- function(input, output) {
  output$table1 <- DT::renderDataTable({
    datatable(mtcars, extensions = 'Select', selection = list(target = "column"), options = list(ordering = FALSE, searching = FALSE, pageLength = 25))
  })

  output$table2 <- DT::renderDataTable({
    subset_table <- mtcars[, input$table1_columns_selected, drop = F]
    datatable(subset_table)
  })
}

shinyApp(ui = ui, server = server)

Note the change in the datatable arguments in output$table1 . Hope this is what you were looking for.

I have tested your code and its working fine for me (see picture below) and i am also using DT package version 0.4.

So my guess is that, its not DT package problem but something else in your global configuration that is causing the issue.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM