[英]In a shiny app, how do you explicitly refer to user selections from selectizeInput to read in specific csv files?
I'm creating a Shiny app with a number of dropdowns using selectizeInput.我正在使用 selectizeInput 创建一个带有多个下拉菜单的 Shiny 应用程序。 One is called "Country" and has a list of countries, the other is called "Year" and has a list of years.
一个叫做“国家”,有一个国家列表,另一个叫做“年”,有一个年份列表。 The app will then populate a few charts based on the data for that country/year combination.
然后,该应用程序将根据该国家/地区组合的数据填充一些图表。 I have one csv file in a folder for every country and every year, and putting all those files together as I have done creates a very slow app, so instead I would like to conditionally read into the server the specific country/year files based on those selections.
我在每个国家和每年的文件夹中都有一个 csv 文件,并将所有这些文件放在一起会创建一个非常慢的应用程序,所以我想有条件地将特定国家/年份文件读入服务器基于那些选择。
The Country input allows multiple selections (up to 5), the Year input only allows one. Country 输入允许多项选择(最多 5 个),Year 输入只允许一项。
All CSV files are formatted like this:所有 CSV 文件的格式如下:
2014_UK.csv
2014_US.csv
2014_SA.csv
2015_UK.csv
2015_US.csv
....
What is the best way to do this?做这个的最好方式是什么?
One way to go about it is to create a reactive
that reads in the data each time one of the inputs is changed.一种方法是创建一个
reactive
,每次更改一个输入时都会读入数据。
# create some fake data
countries <- c('US', 'UK', 'SA')
years <- 2013:2015
x <- paste0(paste(rep(years, each = length(countries)), countries, sep = "_"), '.csv')
for (i in x){
write.csv(data.frame(x=i, y=rnorm(5)), i)
}
library(shiny)
ui <- fluidPage(
selectInput('year', 'year', years),
selectInput('country', 'country', countries, multiple=T), # multiple is T
dataTableOutput('tbl', width='200px')
)
server <- function(input, output){
r <- reactive({
req(input$country) # req country to be not NULL
x <- paste0(input$year, '_', input$country, '.csv') # paste inputs together, maybe more than 1
l <- lapply(x, read.csv) # read in all csvs in x
do.call('rbind', l) # bind them together
})
output$tbl <- renderDataTable(r())
}
shinyApp(ui, server)
In this app, each time one of the inputs is changed, the reactive block is executed and the output$tbl
will render the new data.在此应用程序中,每次更改其中一个输入时,都会执行反应块,并且
output$tbl
将呈现新数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.