rhandsontable 使用 "hide" 列的下拉菜单

rhandsontable using a dropdown to "hide" columns

我有一个要传递给 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 是日期类型,它不会如果选择了“显示第 1 至 5 列”,则查找 column_6。

抱歉,我没有可用的示例,但希望这是有意义的。谢谢!

您可以根据 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)