R闪亮,文件输入显示;上载已完成";在实际完成之前几秒钟
我通常需要将大的(约700MB)csv文件上传到我闪亮的应用程序中。问题是,它显示“上传完成”只需不到3秒左右,而实际上需要大约20秒(我们还通过打印一些数据行来确认) 有解决办法吗R闪亮,文件输入显示;上载已完成";在实际完成之前几秒钟,r,shiny,R,Shiny,我通常需要将大的(约700MB)csv文件上传到我闪亮的应用程序中。问题是,它显示“上传完成”只需不到3秒左右,而实际上需要大约20秒(我们还通过打印一些数据行来确认) 有解决办法吗 ui <- fluidPage( titlePanel("Predictive Models"), # Sidebar layout with input and output definitions ---- sidebarLayout( # Sidebar panel for i
ui <- fluidPage(
titlePanel("Predictive Models"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: Select a file ----
fileInput("file1", "Choose CSV File",
multiple = FALSE,
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv"),
width = "80%")
...
server <- function(input, output) {
values <- reactiveValues(df_data = NULL, station_id= NULL, station_name= NULL, station_data=NULL, processed_data=NULL,df=NULL)
observeEvent(input$file1, {
values$df_data <- read.csv(input$file1$datapath);
output$sum <- renderPrint({
print(head(values$df_data, 10))
})
})
ui上传文件有两个步骤
该文件被放置到由tempdir()定义的临时文件夹中
使用read.csv()将文件读入内存
我们在fileInput中看到的上载栏仅测量将文件上载到服务器和临时目录的时间。不是把它读入记忆的时候
由于read.csv()
会阻塞服务器直到操作完成,因此测量将文件读入内存所需时间的唯一方法是分批读取文件。在每个步骤中,我们都使用progress
记录进度
这是一个示例,它不是最有效的代码
library(shiny)
ui <- fluidPage(
titlePanel("Predictive Models"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: Select a file ----
fileInput("file1", "Choose CSV File",
multiple = FALSE,
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv"),
width = "80%")
),
mainPanel(verbatimTextOutput("sum"))
)
)
server <- function(input, output,session) {
options(shiny.maxRequestSize=800*1024^2)
read_batch_with_progress = function(file_path,nrows,no_batches){
progress = Progress$new(session, min = 1,max = no_batches)
progress$set(message = "Reading ...")
seq_length = ceiling(seq.int(from = 2, to = nrows-2,length.out = no_batches+1))
seq_length = seq_length[-length(seq_length)]
#read the first line
df = read.csv(file_path,skip = 0,nrows = 1)
col_names = colnames(df)
for(i in seq_along(seq_length)){
progress$set(value = i)
if(i == no_batches) chunk_size = -1 else chunk_size = seq_length[i+1] - seq_length[i]
df_temp = read.csv(file_path, skip = seq_length[i], nrows = chunk_size,header = FALSE,stringsAsFactors = FALSE)
colnames(df_temp) = col_names
df = rbind(df,df_temp)
}
progress$close()
return(df)
}
df = reactive({
req(input$file1)
n_rows = length(count.fields(input$file1$datapath))
df_out = read_batch_with_progress(input$file1$datapath,n_rows,10)
return(df_out)
})
observe({
output$sum <- renderPrint({
print(head(df(), 10))
})
})
}
shinyApp(ui,server)
库(闪亮)
谢谢!这对用户来说仍然有点尴尬,因为一个说“上传完成”,而另一个进度条跟踪过程。但肯定比以前好多了:)@Alex我同意。此解决方案主要解释问题发生的原因,它是一个黑客解决方案。通过自定义javascript代码,可能会有更高级的解决方案。