shiny allowling users to choose which columns to display

瘦欲@ 提交于 2019-11-30 16:39:08

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])

      }


    })

  }
))

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]
    })
  }
))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!