在 Shiny 中创建条件/动态 UI 有多种方法(请参见此处)。最直接的通常是renderUI
. 请参阅下文为您提供可能的解决方案。请注意,这需要 Shiny,因此如果您使用 R Markdown,请确保runtime: shiny
在 YAML 标头中指定。
library(shiny)
# I don't have a list of all counties, so creating an example:
county.name = lapply(
1:length(state.name),
function(i) {
sprintf("%s-County-%i",state.abb[i],1:5)
}
)
names(county.name) = state.name
shinyApp(
# --- User Interface --- #
ui = fluidPage(
sidebarPanel(
selectInput(inputId = "state", label = "Choose a state:", choices = state.name),
uiOutput("county")
),
mainPanel(
textOutput("choice")
)
),
# --- Server logic --- #
server = function(input, output) {
output$county = renderUI({
req(input$state) # this makes sure Shiny waits until input$state has been supplied. Avoids nasty error messages
selectInput(
inputId = "county", label = "Choose a county:", choices = county.name[[input$state]] # condition on the state
)
})
output$choice = renderText({
req(input$state, input$county)
sprintf("You've chosen %s in %s",
input$county,
input$state)
})
}
)
希望这可以帮助!