Joe*_*e Z 6 r shiny rhandsontable
我正在制作一个闪亮的应用程序,用户需要在其中选择表格中的下拉选项。我正在使用 rhandsontable,但是似乎我只能为单个列设置一组下拉选项。所以第 1 行与第 800 行具有相同的选项。我希望第 1 行具有与第 800 行不同的下拉选项集。
有没有办法做到这一点?
我想过创建单独的表格并将它们放在一起看起来像一张桌子。只有第一个表会有列标题,它下面的所有其他表都没有列标题。我试图避免这种情况,因为 rhandsontables 具有水平和垂直滚动条,并且没有办法在多个表之间同步滚动条。那会让“一张桌子”看起来有点不对劲。实际上,将所有数据放在一个表中会更好看且功能更好。
我在下面有一个超级简单的例子:
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)
Run Code Online (Sandbox Code Playgroud)
我希望下拉选项只包含对象列值为“汽车”的所有行的“轮胎”、“雨刷”和“车头灯”。因为汽车永远不需要排水沟或地毯,所以我不希望用户能够选择这些选项中的任何一个。
对于“房子”是对象列中的值的每一行,用户应该只在下拉列表中显示两个选项......“排水沟”和“地毯”。这将有助于避免用户错误。
这是基于我在这里分享的示例(以及上面提到的@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)
Run Code Online (Sandbox Code Playgroud)
编辑: 在这里您可以找到依赖 rhandsontable 下拉列表的通用方法。