1

I am dabbling with the datatable feature in shiny and I am interested in creating a wellpanel or a sidepanel that lists all the columns of a datatable and allows users to choose which columns they want to see on the datatable.

Right now this code below displays all the columns of toy dataset mtcars

library(shiny)

runApp(list(
  ui = basicPage(
    h2('The mtcars data'),
    dataTableOutput('mytable')
  ),
  server = function(input, output) {
    output$mytable = renderDataTable({
      mtcars
    })
  }
))

I am interested in providing the users the ability to turn these columns either on or off using a checkbox

  [1] "mpg"  "cyl"  "disp" "hp"   "drat"
  [6] "wt"   "qsec" "vs"   "am"   "gear"
  [11] "carb"

Any help on addressing this issue is much appriciated. Thanks in advance.

Jill Sellum
  • 319
  • 2
  • 4
  • 14

2 Answers2

11

Here is an example. It uses selectInput to select columns, and displays all columns by default until you select one or more specific columns.

library(shiny)
runApp(list(
  ui = basicPage(
    selectInput("select", "Select columns to display", names(mtcars), multiple = TRUE),
    h2('The mtcars data'),
    dataTableOutput('mytable')
  ),
  server = function(input, output) {
    output$mytable = renderDataTable({
      columns = names(mtcars)
      if (!is.null(input$select)) {
        columns = input$select
      }
      mtcars[,columns,drop=FALSE]
    })
  }
))
Xiongbing Jin
  • 11,779
  • 3
  • 47
  • 41
  • this looks sensible. – Jill Sellum Apr 22 '16 at 06:04
  • 2
    I like this example, it's simple. One question: what if the file was imported into the app via `fileInput`? How would you refer to the file in `selectInput` on `ui` side and `columns` on server side? – jvalenti Feb 12 '20 at 19:39
3

My example uses checkboxGroupInput to select multiple columns

library(shiny)

vchoices <- 1:ncol(mtcars)
names(vchoices) <- names(mtcars)

runApp(list(
  ui = basicPage(
    h2('The mtcars data'),
    checkboxGroupInput("columns","Select Columns",choices=vchoices,inline = T),
    dataTableOutput('mytable')


  ),
  server = function(input, output) {

    observeEvent(input$columns,{
      cols <- as.numeric(input$columns)
      if(length(input$columns) == 1){
        df <- data.frame(mtcars[,cols])
        names(df) <- names(mtcars)[cols]
        output$mytable = renderDataTable(df)

      }else{
        output$mytable = renderDataTable(mtcars[,cols])

      }


    })

  }
))
Adam Birenbaum
  • 940
  • 9
  • 23
  • i like your approach, I plan on adding a download button on the top such that users can download the filtered datatable. If your code lays out the columns like that on the top my fear is that there wont be any space for the download option or the alignment might get screwed. – Jill Sellum Apr 22 '16 at 06:03
  • The shiny documentation on layouts might be something you should look into. [Link](http://shiny.rstudio.com/articles/layout-guide.html) – Adam Birenbaum Apr 22 '16 at 06:08