下面的R闪亮脚本创建了三个selectInput,使得每个selectInput的值取决于前一个selectInput的输入值。例如。在脚本中的数据中,"值"列值取决于" Candy"专栏和" Candy"列值取决于"品牌"。问题是,我是否选择" Mars"或者" Netle"品牌价值"品牌"专栏,相应的" Candy"价值" 100Grand"对于两者都是相同的,因此我没有看到值列中的更改,因为selectInput正在读取相同的值。请帮我解决这个问题,同时请确保脚本不会变慢。感谢。
candyData <- read.table(
text = "
Brand Candy value
Mars 100Grand Choc1
Netle 100Grand Choc2
Nestle Crunch Choc3",
header = TRUE,
stringsAsFactors = FALSE)
library(shiny)
library(shinydashboard)
submenuUI <- function(id) {
ns <- NS(id)
tagList(
box(title = "Data", status = "primary", solidHeader = T, width = 12,
fluidPage(
fluidRow(
column(2,offset = 0, style='padding:1px;',
selectInput(ns("Select1"),"select1",unique(candyData$Brand))),
column(2,offset = 0,
style='padding:1px;',selectInput(ns("Select2"),"select2",choices = NULL)),
column(2, offset = 0,
style='padding:1px;',selectInput(ns("Select3"),"select3",choices=NULL ))
)))
)
}
submenuServ <- function(input, output, session){
observeEvent(input$Select1,{
updateSelectInput(session,'Select2',
choices=unique(candyData$Candy[candyData$Brand==input$Select1]))
})
observeEvent(input$Select2,{
updateSelectInput(session,'Select3',
choices=unique(candyData$value[candyData$Brand==input$Select1 &
candyData$Candy==input$Select2]))
})
}
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(
sidebarMenu(
shinyjs::useShinyjs(),
id = "tabs",
menuItem("Charts", icon = icon("bar-chart-o"),
shinyjs::hidden(menuSubItem("dummy", tabName = "dummy")),
menuSubItem("Sub-item 1", tabName = "subitem1")
))),
dashboardBody(
tabItems(tabItem("dummy"),
tabItem("subitem1", submenuUI('submenu1'))
)
))
server <- function(input, output,session) {
callModule(submenuServ,"submenu1")
}
shinyApp(ui = ui, server = server)
答案 0 :(得分:2)
您只需在input$Select1
中添加observeEvent
即可更新select3
submenuServ <- function(input, output, session){
observeEvent(input$Select1,{
updateSelectInput(session,'Select2',
choices=unique(candyData$Candy[candyData$Brand==input$Select1]))
})
observeEvent(c(input$Select1, input$Select2),{
updateSelectInput(session,'Select3',
choices=unique(candyData$value[candyData$Brand==input$Select1 &
candyData$Candy==input$Select2]))
})
}
然后您可以将observeEvent
转换为observe