0

我已经针对我的问题查看了类似的帖子,但没有任何帮助,而且我已经没有耐心了。

我有一个非常简单的应用程序,我试图在其中找到选定的美国州内的所有县。我在 UI 中使用 SelectInput 让用户选择他们想要的州,并在服务器中使用 UpdateSelectInput 以便用户可以从他们的州选择中选择他们想要的县。

这是我的简化数据的样子:

**STATE_NAME      NAMELSAD**
Alabama            Clay County  
Alabama            Marengo County
Arkansas           Scott County

我的代码如下所示:

全球.r

library(shiny)
library(leaflet)
library(sp)
library(rgdal)
library(htmltools)
library(DT)
library(ggplot2)
library(shinythemes)

path <- "C:/Users/user/Desktop/Countyapp/Countyapp/test_covid/"
setwd(path)

counties <- read.csv("us_counties1.csv")

用户界面.r

ui <- fluidPage(
        selectInput(inputId = "selectstate", label = "Select State", choices = (counties$STATE_NAME)),
        selectInput(inputId = "selectcounty", label =  "Select County", choices = NULL)
)

最后,server.R

server <- function(session, input, output) {

    observe({
        updateSelectInput(session, "selectcounty", "Select County", 
                          choices = counties$NAMELSAD[counties$STATE_NAME==input$STATE_NAME])
    })

}

shinyApp(ui = ui, server = [enter image description here][1]server) 

基本上,我的第一个 SelectInput 工作,你可以选择任何你想要的状态。但是第二个选择器是空白的!为什么。我的观察功能有问题,但我一直坐在这里,没有可能的解决方案。如果可以的话请帮忙!谢谢!

4

3 回答 3

1

天哪,我是愚蠢的。

这是因为我在观察事件中将输入命名错误。

让它工作。回答:

  observe({
        updateSelectInput(session, "selectcounty", "Select County", 
                          choices = counties$NAMELSAD[counties$STATE_NAME==input$selectstate])
    })
于 2020-06-09T23:09:13.807 回答
0

observe()函数的目的是观察反应表达式的变化。但是,updateSelectInput()它不是您编写的反应式表达式,因为其中的任何表达式都不涉及任何反应式值或表达式。

相反,您应该observe()输入更改的值,例如,如下所示:

observe({
 if(input$selectstate != ""){
 updateSelectInput(session, "selectcounty", "Select County", 
                          choices = counties$NAMELSAD[counties$STATE_NAME==input$selectstate,])
 }
else {
 updateSelectInput(session, "selectcounty", "Select County", 
                          choices = "Select State")
 }
})

in 的表达式observe现在是响应式的,因为input它是响应式的。

请参阅此答案以获得出色的讨论。

于 2020-06-09T22:50:09.013 回答
0

而不是observe,尝试使用observeEvent

还有一个错字,input$STATE_NAME应该在哪里input$selectstate

下面是一个最小的工作示例:

library(shiny)

#Create your dataframe (runs once when app starts)
counties <- data.frame(
    STATE_NAME = c('Alabama', 'Alabama', 'Arkansas'),
    NAMELSAD   = c('Clay County', 'Marengo County', 'Scott County'),
    stringsAsFactors = FALSE
)

#UI
ui <- fluidPage(

    selectInput(inputId = "selectstate",  label = "Select State",  choices = (counties$STATE_NAME)),
    selectInput(inputId = "selectcounty", label = "Select County", choices = NULL)

)

#Server
server <- function(input, output, session) {

    #Runs when input$selectstate changes
    observeEvent(input$selectstate, {

        updateSelectInput(session, inputId = "selectcounty", label = "Select County", choices = counties[counties$STATE_NAME == input$selectstate,]$NAMELSAD)

    })

}

shinyApp(ui, server)
于 2020-06-09T22:58:13.637 回答