【发布时间】:2018-04-03 00:48:49
【问题描述】:
在我之前的post 中,我能够使用for 循环在Shiny 中上传多个文件、处理文件、rbind 并返回一个csv 文件下载。感谢@SBista的贡献。但是,因为我必须一次上传很多文件(总大小约为 50 - 100mb),我发现运行闪亮的应用程序非常慢,这可能是由于for 循环。我知道lapply() 在reading multiple csv files 循环中比for 循环更快,但是在我的代码中应用lapply() 在运行应用程序后会出现错误(错误:无效的'description' 参数)。任何帮助将不胜感激。这是我的dummy file,这是我的代码:
library(shiny)
ui <- fluidPage(
fluidPage(
titlePanel("MY CSV FILES MERGER"),
sidebarLayout(
sidebarPanel(
fileInput("file1",
"Choose CSV files from a directory",
multiple = TRUE,
accept=c('text/csv',
'text/comma-separated-values,text/plain',
'.csv')),
downloadButton('downloadData', 'Download')
),
mainPanel(
tableOutput('contents')
)
)
)
)
library(shiny)
library(dplyr)
options(shiny.maxRequestSize = 100*1024^2)
server <- function(input, output) {
getData <- reactive({
inFile <- input$file1
if (is.null(inFile)){
return(NULL)
}else {
files3 = lapply(inFile, function(y){
JSON_csv = read.csv(y, header = TRUE)
lastrow = nrow(JSON_csv)
shift = function(x, n){
c(x[-(seq(n))], rep(NA, n))
}
JSON_csv$companyID1 = shift(JSON_csv$companyID1, 1)
JSON_csv = JSON_csv[-lastrow, ]
JSON_csv
}
)
do.call(rbind, files3)
}
})
output$contents <- renderTable(
getData()
)
output$downloadData <- downloadHandler(
filename = function() {
paste("data-", Sys.time(), ".csv", sep="")
},
content = function(file) {
write.csv(getData(), file, row.names=FALSE)
})
}
shinyApp(ui = ui, server = server)
使用for 循环,此代码可以工作,但在处理多个 50-100mb 的 csv 文件时速度非常慢:
library(shiny)
library(dplyr)
server <- function(input, output) {
getData <- reactive({
inFile <- input$file1
if (is.null(inFile)){
return(NULL)
}else {
# browser()
numfiles = nrow(inFile)
kata_csv1 = list()
for (i in 1:numfiles)
{
JSON_csv = read.csv(input$file1[[i, 'datapath']], header = TRUE)
lastrow = nrow(JSON_csv)
shift = function(x, n){
c(x[-(seq(n))], rep(NA, n))
}
JSON_csv$companyID1 = shift(JSON_csv$companyID1, 1)
kata_csv1[[i]] = JSON_csv[-lastrow, ]
}
# browser()
do.call(rbind, kata_csv1)
}
})
output$contents <- renderTable(
getData()
)
output$downloadData <- downloadHandler(
filename = function() {
paste("data-", Sys.Date(), ".csv", sep="")
},
content = function(file) {
write.csv(getData(), file, row.names=FALSE)
})
}
shinyApp(ui = ui, server = server)
【问题讨论】: