我已经在类似的帖子中找到了解决我的问题的方法,但是没有任何帮助,而且我已经忍耐不住了。
我有一个非常简单的应用程序,我试图在其中查找所选美国州内的所有县。我在用户界面中使用SelectInput供用户选择所需的州,并在服务器中使用UpdateSelectInput使用户可以从状态选择中选择所需的县。
这是我的简化数据的样子:
**STATE_NAME NAMELSAD**
Alabama Clay County
Alabama Marengo County
Arkansas Scott County
我的代码如下:
global.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")
UI.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工作正常,您可以选择所需的任何状态。但是第二个选择器为空! y。 我的观察功能出了点问题,但是我一直坐在这里,没有可能的解决方案。 如果可以的话请帮忙!谢谢!
答案 0 :(得分:1)
天哪,我很愚蠢。
这是因为我在观察事件中将输入命名错误。
让它正常工作。答案:
observe({
updateSelectInput(session, "selectcounty", "Select County",
choices = counties$NAMELSAD[counties$STATE_NAME==input$selectstate])
})
答案 1 :(得分: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")
}
})
observe
中的表达式现在是反应性的,因为input
是反应性的。
请参见this answer进行出色的讨论。
答案 2 :(得分: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)