如何在 R Markdown 中创建条件 selectInput 小部件?

How can I create a conditional selectInput widget in R Markdown?

目的是从一个州中选择一个县。我首先创建一个 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的使用是有问题的,但我没有别的想法。

感谢您的宝贵时间!

有多种方法可以在 Shiny 中创建 conditional/dynamic UI(参见 here)。最直接的通常是renderUI。请参阅下文,了解适合您的可能解决方案。请注意,这需要 Shiny,因此如果您使用 R Markdown,请确保在 YAML header.

中指定 runtime: shiny
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)
    })
  }

)

希望对您有所帮助!