Vincent 的解决方案使用两个按钮,一个用于计算的操作按钮和一个用于下载的下载按钮,这是我使用的解决方案。该解决方案的另一个好处是shinyIncubator 包中也包含进度条。
对我的代码的解释,以防其他人想做同样的事情:
ui.R 有一个操作按钮和一个动态下载按钮:
actionButton("makePlots", "Calculate Results"),
uiOutput("download_button")
以及进度条的进度初始化:
mainPanel(
progressInit(),
uiOutput("mytabs")) # dynamic rendering of the tabs
server.R 稍微复杂一些。因此,仅当有要下载的内容时才会显示下载按钮,我使用了动态 uiOutput 和以下代码:
output$download_button <- renderUI({
if(download){
downloadButton("downloadPlots", "Download Results")
}
})
下载按钮仅在以下情况下显示download==TRUE
。在 server.R 启动时,变量被初始化:download<-FALSE
由于每次单击操作按钮都会增加 1,因此我添加了一个计数器(初始值 0),该计数器在每次“使用”操作按钮后都会增加。原因是第一个 if 语句。
makePlots<-reactive({
if(input$makePlots>counter){ # tests whether action button has been clicked
dir.create("new_directory_for_output")
withProgress(session, min=1, max=15, expr={ # setup progress bar
for(i in 1:15){
png(paste0("new_directory_for_output/plot",i,".png"))
plot(i)
dev.off()
setProgress(message = 'Calculation in progress',
detail = 'This may take a while...',
value=i)
} # end for
}) # end progress bar
counter<<-counter+1 # needs the <<- otherwise the value of counter
# is only changed within the function
download<<-TRUE # something to download
} # end if
}) # end function
在此阶段,函数 makePlots() 没有输出,也没有在任何地方调用,因此它什么也不做。因此,我将 makePlots() 放在每个选项卡的开头,这样无论用户位于哪个选项卡上,一旦单击操作按钮,就会制作并保存绘图。
最后一块拼图是下载处理程序:
output$downloadPlots <- downloadHandler(
filename = function() { my_filename.zip },
content = function(file){
fname <- paste(file,"zip",sep=".")
zip(fname,new_directory_for_output) # zip all files in the directory
file.rename(fname,file)
unlink(new_directory_for_output,recursive = TRUE) # delete temp directory
download<<-FALSE # hide download button
}
) # end download handler