我正在制作一个闪亮的应用程序,用户需要在其中选择表格中的下拉选项。我正在使用rhandsontable,但是似乎只能为一个列设置一组下拉选项。因此,第1行与第800行具有相同的选项。我希望第1行与第800行具有不同的下拉选项集。
有没有办法做到这一点?
我已经考虑过创建单独的表并将它们推在一起看起来像一个表。只有第一个表将具有列标题,而其下的所有其他表将没有列标题。我试图避免这种情况,因为流变台具有水平和垂直滚动条,并且没有办法在多个表之间同步滚动条。这会使“一张桌子”看起来有些偏离。实际上,将所有数据都放在一个表中会看起来和功能更好。
我在下面有一个非常简单的例子:
require(shiny)
require(rhandsontable)
ui <- fluidPage(
hr(""),
# Display table
mainPanel(rHandsontableOutput("ExampleTable"))
)
server <- function(input, output) {
output$ExampleTable <- renderRHandsontable({
# creating table that will be displayed
df <- data.frame(Object = c("car", "car", "car", "house", "house", "house"), Needs = NA, stringsAsFactors = FALSE)
# defining dropdown options
dropdownOptions <- c("tires", "wipers", "headlights", "gutters", "carpet")
rhandsontable(df, rowHeaders = NULL, stretchH = "all") %>%
hot_col("Object", readOnly = TRUE) %>%
hot_col("Needs", type = "dropdown", source = dropdownOptions)
})
}
# Run the application
shinyApp(ui = ui, server = server)
我希望对于“对象”列的值为“汽车”的所有行,下拉选项仅包括“轮胎”,“雨刮器”和“前灯”。由于汽车永远不需要装订线或地毯,因此我不希望用户能够选择这些选项中的任何一个。
对于“ house”是“对象”列中值的每一行,用户应该只在下拉菜单中显示两个选项:“装订线”和“地毯”。这将有助于避免用户错误。
答案 0 :(得分:1)
这是基于我分享的here(和上面提到的@Ben)的示例的有效解决方案:
library(shiny)
library(rhandsontable)
ui <- fluidPage(
hr(),
# Display table
mainPanel(rHandsontableOutput("ExampleTable"))
)
server <- function(input, output) {
# creating table that will be displayed
DF <- reactiveVal(data.frame(Object = c("car", "car", "car", "house", "house", "house"), Needs = NA_character_, stringsAsFactors = FALSE))
# update df() on user changes
observeEvent(input$ExampleTable, {
DF(hot_to_r(input$ExampleTable))
})
output$ExampleTable <- renderRHandsontable({
# defining dropdown options
carOptions <- c(NA_character_, "tires", "wipers", "headlights")
houseOptions <- c(NA_character_, "gutters", "carpet")
tmpExampleTable <- rhandsontable(DF(), rowHeaders = NULL, stretchH = "all", selectCallback = TRUE, width = 300, height = 300) %>%
hot_col("Object", readOnly = TRUE) %>%
hot_col("Needs", allowInvalid = FALSE, type = "dropdown", source = NA_character_, readOnly = TRUE)
if(!is.null(input$ExampleTable_select$select$r)){
selectedObject <- DF()[input$ExampleTable_select$select$r, "Object"]
if(selectedObject == "car"){
tmpExampleTable <- hot_col(tmpExampleTable, col = "Needs", allowInvalid = FALSE, type = "dropdown", source = carOptions) %>% hot_cell(row = input$ExampleTable_select$select$r, col = "Needs", readOnly = FALSE)
}
if(selectedObject == "house"){
tmpExampleTable <- hot_col(tmpExampleTable, col = "Needs", allowInvalid = FALSE, type = "dropdown", source = houseOptions) %>% hot_cell(row = input$ExampleTable_select$select$r, col = "Needs", readOnly = FALSE)
}
}
tmpExampleTable
})
}
# Run the application
shinyApp(ui = ui, server = server)