问题
The R shiny script below creates three selectInputs such that the values of each selectInput depend upon the input value of the previous selectInput. E.g. in the data in the script, "value" column values depend on "Candy" column and "Candy" column values depend on the "Brand". The issue is that, whether I select "Mars" or "Netle" value in the "Brand" column, The corresponding "Candy" value "100Grand" is same for both, hence I do not see a change in the value column as the selectInput is reading the same value. Kindly help me to fix this, also please ensure the script does not become slow. Thanks.
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)
回答1:
You can just add input$Select1
in your observeEvent
to update 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]))
})
}
If you want, you can convert the observeEvent
to observe
:
observe({
updateSelectInput(
session, 'Select3',
choices= unique(candyData$value[candyData$Brand==input$Select1 & candyData$Candy==input$Select2])
)
})
来源:https://stackoverflow.com/questions/48519138/selectinput-value-update-based-on-previous-selectinput-in-r-shiny