【问题标题】:rhandsontable using a dropdown to "hide" columnsrhandsontable 使用下拉菜单“隐藏”列
【发布时间】:2020-10-30 03:50:02
【问题描述】:

我有一个要传递给 rhandsontable 的数据框。假设它有 10 列。我有一个包含 3 个选项的下拉菜单:

  1. 显示第 1 到 5 列
  2. 显示第 1、5 和 10 列
  3. 显示第 6 到 10 列

默认情况下,当 rhandsontable 加载时,它将显示所有 10 列。当用户在下拉列表中选择三个选项之一时,我想使用hot_col(col = col_name, width = 0.5)隐藏某些列

例如,如果用户选择选项 1 - 显示第 1 到 5 列,隐藏第 6 到 10 列将如下所示:

rhandsontable(df) %>%
hot_col(col = column_6, width = 0.5) %>%
hot_col(col = column_7, width = 0.5) %>%
hot_col(col = column_8, width = 0.5) %>%
hot_col(col = column_9, width = 0.5) %>%
hot_col(col = column_10, width = 0.5)

我尝试使用以下内容过滤数据集:

df <- if (input$dropdown == "Show columns 1 through 5") {df %>% select(1:5)}
else if (input$dropdown == "Show columns 1, 5 and 10") {df %>% select(1, 5, 10)}
else if (input$dropdown == "Show columns 6 through 10") {df %>% select(6:10)}
else {df %>% select(1:10)}

仅适用于显示特定列,但我有 hot_col 特定于不同列的规则,因为如果我有一条规则说 column_6 是日期类型,它不会找到 column_6 如果“显示列 1 到选择 5"。

对不起,我没有一个可行的例子,但希望这是有道理的。谢谢!

【问题讨论】:

    标签: drop-down-menu shiny filtering hide rhandsontable


    【解决方案1】:

    您可以从selectInput 确定应隐藏哪些列,然后在renderRHandsontable 调用中使用此信息来动态隐藏列:

    library(shiny)
    library(rhandsontable)
    ui <- fluidPage(
      fluidRow(
        column(width = 6,
               selectInput( inputId = "columns", 
                            label = "select columns",
                            choices = c("all", "first half", "second half")
               )
               
               
        ),
        rHandsontableOutput("table")
      )
    )
    
    server <- function(input, output, session) {
      
      output$table <- renderRHandsontable({
        output <- rhandsontable(mtcars[, 1:4])
        
        # determine the columns to show
        if (input$columns == "all") columns_to_hide <- NULL
        if (input$columns == "first half") columns_to_hide <- 3:4
        if (input$columns == "second half") columns_to_hide <- 1:2
        
        used_colnames <- colnames(mtcars[, 1:4])
        
        if (!is.null(columns_to_hide)) {
          for (col_name in used_colnames[columns_to_hide]) {
            output <- output %>% hot_col(col = col_name, width = 0.5)
          }
        }
        
        output
      })
    }
    shinyApp(ui, server)
    

    【讨论】:

    • 这正是我所需要的。谢谢你。后续问题 - 您知道在更改 rhandsontable 时捕获列名的方法吗?我知道我可以使用input$table_select$select$c 捕获列号,但我正在寻找名称。再次感谢!
    • 不,对不起。但是如果你有列号,你可以很容易地得到你的表的列名,并使用这个数字来索引这些名称。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-18
    • 2014-03-31
    • 1970-01-01
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    相关资源
    最近更新 更多