r - R Shiny - 选择城市取决于使用 selectInput 选择的省份
问题描述
我正在尝试根据省列和城市列对数据框进行子集化。在闪亮中,我想让用户使用 selectInput UI 选择省然后选择城市。
这是数据框的样子。
列InfoTemp[2]
是市,InfoTemp[3]
是省。
数据集很大,它们实际上有很多层次。
年秋 InfoTemp[2] InfoTemp[3] 1913 8.9 肖尼根湖 BC 1914 9.5 肖尼根湖 BC 1915 9.3 肖尼根湖 BC 1916 8.5 肖尼根湖 BC 1917 9.9 肖尼根湖 BC 1918 -9999.9 肖尼根湖 BC
最终,这是我打算去的一个地块(对于一个城市)。
这是到目前为止的代码,没有做任何事情......
服务器.R
library(shiny)
shinyServer(function(input, output) {
#MeanTemp
load("CanadianMeanTemp.Rdata")
province = input$provinces
city = input$cities
output$distPlot <- renderPlot({
MeanTemp_province = MeanTemp[grep(c(province), MeanTemp$`InfoTemp[3]`),]
MeanTemp_city = MeanTemp_province[grep(c(city), MeanTemp$`InfoTemp[2]`),]
plot(MeanTemp_city$Year, MeanTemp_city$Annual, type = "l")
lines(supsmu(MeanTemp_city$Year, MeanTemp_city$Annual), col = 2)
})
})
用户界面
library(shiny)
shinyUI(fluidPage(
titlePanel("Temperature"),
sidebarLayout(
sidebarPanel(
selectInput('provinces', 'Province', choices = levels(MeanTemp$`InfoTemp[3]`)),
conditionalPanel(
condition = "input.provinces == true",
selectInput('cities', 'City', choices = levels(MeanTemp_province$`InfoTemp[2]`))
)
),
mainPanel(
plotOutput("distPlot")
)
)
))
解决方案
代码
library(shiny)
city_data <- expand.grid(Year = seq.Date(as.Date("1990/1/1"),
as.Date("2000/1/1"), by = "year"),
Province = LETTERS[1:3],
City_Counter = 1:4)
city_data$City <- paste(city_data$Province, city_data$City_Counter, sep = "_")
city_data$Autumn <- runif(NROW(city_data), 10, 100)
ui <- fluidPage(
selectInput("province", "Select province:", unique(city_data$Province)),
selectInput("city", "Select city:", unique(city_data$City)),
plotOutput("plot")
)
server <- function(input, output, session) {
get_filtered_data <- reactive({
city_data[city_data$Province %in% input$province &
city_data$City %in% input$city, , drop = FALSE]
})
observe({
updateSelectInput(session,
"city",
choices = unique(city_data[city_data$Province %in%
input$province, "City"]))
})
output$plot <- renderPlot({
my_data <- get_filtered_data()
req(NROW(my_data) > 0)
plot(my_data$Year, my_data$Autumn, type = "l")
})
}
shinyApp(ui, server)
一些备注
- 我使用了 b/c
updateSelectInput
而不是一种方法,我觉得在最终只进行更改uiOutput
时重新渲染整个输入是一种矫枉过正的做法。choices
- 我在这里使用 base R 进行子集化,但
tidyverse
如果需要,这可以很容易地用语法替换 - 我在过滤中使用
%in%
而不是==
,以便在需要时扩展它以在多面图中显示多个城市/省
推荐阅读
- typescript - AWS CDK:如果 Typescript 中的基本路径为空,则只允许一个基本路径映射
- flutter - Flutter 使用谷歌登录错误:登录失败
- php - 我收到警告:计数():参数错误
- javascript - 如何在不输入所有字母的情况下在 JavaScript 中生成随机 a - z 字母(1 个字母)?
- amazon-web-services - 亚马逊子域上 ALB 的 SSL 证书?
- ios - 关于使用 Keychains 和 Provisioning Profiles Management 的 Jenkins 自动包设置
- spring-boot - kubernetes 上的 Mariadb 读取通信包时出错
- javascript - 无法缩小 javascript 类
- python - Textarea 字段返回字符串字典以在 django 中转换字典
- javascript - 动态 TypeScript 接口上的访问属性