问题
In a snippet of code below from my RMarkdown
\ flexdashboard
code with shiny
, I need to modify the choices
for the second selectInput()
function, based on the selection made at the first selectInput()
function.
selectInput('theme', 'Select theme:',
choices = c(dtThemes$Theme %>% unique()))
selectInput('question', 'Select Question:',
choices = c(dtQuestions$Question %>% unique())) # This works
#choices = strQuestions) # This does not work
strQuestions <- reactive({
nQuestions <- dtThemes[Theme == input$theme, Q2018]
dtQuestions[nQuestion %in% nQuestions, strQuestion]
})
How do I do that?
Encapsulating code inrenderUI()
did not help:
renderUI({
selectInput('question', 'Select Question:',
strQuestions(), width="100%")
})
回答1:
You can use updateSelectInput
. Below is a small example where the choices for Option B are a sequence of the length specified in Option A:
library(shiny)
ui <- fluidPage(
selectInput("A", "Option A", choices = 1:10),
selectInput("B", "Option B", choices = NULL)
)
server <- function(input, output, session) {
observe({
choices_B <- seq(as.numeric(input$A))
updateSelectInput(session, "B", choices = choices_B)
})
}
shinyApp(ui, server)
回答2:
I've further studied this post: Create reactive selectInput - flexdashboard with Shiny and was able to figure out how to make my code work:
selectInput('theme', 'Select theme:',
choices = c("All", dt$Theme %>% unique()), selected="All")
dt.subset<- reactive({
if (input$theme=="All") {
dt
}else{
dt[Theme == input$theme]
}
})
renderUI({
selectInput('question', 'Select Question:',
choices = (dt.subset()$Question ) %>% unique(),
selected = ( (dt.subset()$Question ) %>% unique() )[1])
})
}
The trick is that you need to have a default selected
value. Otherwise,the code crashes.
Note also I'musing data.table
for dt
.
来源:https://stackoverflow.com/questions/56027198/how-to-do-nested-selections-selectinput-in-rmarkdown-with-shiny