下面的 R闪亮脚本创建了三个 selectInput,使得每个 selectInput 的值取决于前一个 selectInput 的输入值。例如。在脚本的数据中,“value”列值取决于“Candy”列,“Candy”列值取决于“Brand”。问题是,无论我在“Brand”列中选择“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)
您只需在
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
:
observe({
updateSelectInput(
session, 'Select3',
choices= unique(candyData$value[candyData$Brand==input$Select1 & candyData$Candy==input$Select2])
)
})