0

目的是从一个州中选择一个县。我首先创建一个selectInput用于选择状态的小部件。然后我创建一个selectInput小部件,用于从所选州中选择一个县。在 R Markdown 中,代码如下:

inputPanel(
   selectInput(inputId = "State", label = "Choose a state:", choices = state.name),
   selectInput(inputId = "County", label = "Choose a county:", choices = input.State)
)

我想使用input.State是有问题的,但我没有任何其他想法。

谢谢你的时间!

4

1 回答 1

1

在 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)
    })
  }

)

希望这可以帮助!

于 2020-06-16T04:48:05.793 回答