【问题标题】:How can I create a conditional selectInput widget in R Markdown?如何在 R Markdown 中创建条件 selectInput 小部件?
【发布时间】:2020-10-05 10:55:04
【问题描述】:

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

感谢您的宝贵时间!

【问题讨论】:

    标签: r shiny markdown selectinput


    【解决方案1】:

    有多种方法可以在 Shiny 中创建条件/动态 UI(请参阅 here)。最直接的通常是renderUI。请参阅下文为您提供可能的解决方案。请注意,这需要 Shiny,因此如果您使用 R Markdown,请确保在 YAML 标头中指定 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)
        })
      }
    
    )
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-25
      • 2018-05-25
      • 2017-11-30
      • 2017-06-08
      • 2021-11-15
      • 2018-07-07
      • 2016-11-18
      相关资源
      最近更新 更多