【问题标题】:Shiny: in search of simple selectInput dependency solutionShiny:寻找简单的 selectInput 依赖解决方案
【发布时间】:2020-11-08 10:44:06
【问题描述】:

我正在尝试为“县”创建一个简单的 selectInput 依赖函数,该函数依赖/反应用户选择的“状态”。因此,用户在第一个下拉框中选择一个州,然后县下拉框应填充该州的县。然后为所选县创建病例数图表。到目前为止,我一直在寻找最好的方法来做这件事,但没有运气。

以下当前形式的应用程序正在“工作”,但没有依赖关系。所以一旦选择了州,美国所有的县仍然在列表中。我知道问题在于县的 selectInput 语句——我只是不确定哪个是使其依赖于州的最佳方式。我摸索了无数在线示例,但它们似乎不合适。非常感谢任何建议。

library(shiny)
library(dplyr)
library(ggplot2)

usdata <- read_csv("countyout.csv")

ui <- fluidPage(
   titlePanel("US Counties"),

  sidebarPanel(
    selectInput("state", "Select State:", choices = unique(as.character(usdata$state))),
    selectInput("county", "Select County:", choices = unique(as.character(usdata$county)))),
  
  mainPanel(
    plotOutput('casesplot', height = "300px")))

server <- function(input, output) {

  filtered <- reactive ({
     usdata %>%
      filter(state == input$state) %>%
      filter(county == input$county)
  })
  output$casesplot <- renderPlot({
      ggplot(data = filtered(), aes(x=date, y=cases)) + 
      geom_bar(stat = "identity")
  })
  }
shinyApp(ui = ui, server = server)

【问题讨论】:

  • 最近有一个问题,其中提供了与此处相关的示例的答案:stackoverflow.com/questions/62293044/… ... 使用updateSelectInput 在选择州时更新县列表...这样做帮忙?
  • 不敢相信我没有偶然发现那个线程。同样的问题,你的建议也对我有用。谢谢!附言有没有办法让我将您​​的评论标记为解决方案? -- 我是 stackoverflow 的新手。
  • 请随时发布您自己的答案,并附上适合您的代码。这可能有助于其他人在未来解决同样的问题。

标签: r shiny shiny-reactivity


【解决方案1】:

感谢 Ben 为我指明了正确的方向(请参阅他评论中的链接)。我基本上需要将ui中的第二个selectInput语句更改为:

selectInput("countyin", "Select County", choices = NULL)

然后在服务器中添加一个观察语句以使选择具有反应性:

observe({
    updateSelectInput(session, "countyin", "Select County", 
         choices = usdata[usdata$state == input$statein,]$county)
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 2014-07-20
    • 2017-07-27
    • 1970-01-01
    相关资源
    最近更新 更多