【问题标题】:shiny allowling users to choose which columns to display闪亮的允许用户选择要显示的列
【发布时间】:2016-08-15 13:23:48
【问题描述】:

我正在涉足 Shiny 中的数据表功能,并且我有兴趣创建一个井面板或侧面板来列出数据表的所有列,并允许用户选择他们希望在数据表上看到的列。

现在下面这段代码显示了玩具数据集mtcars的所有列

library(shiny)

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

我有兴趣让用户能够使用复选框打开或关闭这些列

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

非常感谢任何有关解决此问题的帮助。提前致谢。

【问题讨论】:

    标签: r datatable shiny dt


    【解决方案1】:

    我的示例使用checkboxGroupInput 选择多个列

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

    【讨论】:

    • 我喜欢你的方法,我计划在顶部添加一个下载按钮,以便用户可以下载过滤后的数据表。如果您的代码在顶部列出了类似的列,我担心下载选项不会有任何空间,否则对齐可能会出错。
    • 关于布局的闪亮文档可能是您应该研究的内容。 Link
    【解决方案2】:

    这是一个例子。它使用selectInput 选择列,并默认显示所有列,直到您选择一个或多个特定列。

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

    【讨论】:

    • 这看起来很明智。
    • 我喜欢这个例子,它很简单。一个问题:如果文件通过fileInput 导入应用程序怎么办?您如何在ui 端和columns 在服务器端引用selectInput 中的文件?
    猜你喜欢
    • 2012-11-13
    • 2021-06-12
    • 2018-06-27
    • 2015-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    相关资源
    最近更新 更多