[英]Saving temp files on R Shiny server
我一直在尝试解决开发我的第一个 R Shiny 应用程序时出现的问题。 我的应用程序可以在我的笔记本电脑上运行,但是当我将它上传到 Shiny 服务器上时我无法让它运行。 我希望应用程序在服务器上创建散点图的临时文件 plotOut,然后通过单击“下载散点图”按钮或自动将其导出到 Excel 文件。 我在下面的 reprex 中发布了我的最佳尝试。 我相信我需要以某种方式使用 tempdir(),但不确定如何使用。 提前致谢
“ui.R”
library(tidyverse)
library(openxlsx)
ui <- fluidPage(
fluidRow("This is a simplified app to reproduce the difficulties in saving and downloading files on the Shiny server",
plotOutput("plot", height = 350),
downloadButton('downloadPlot1', "Download ScatterPlot"),
downloadButton(
'dl_excel',
'Download Results (.xlsx)'
)
)
)
“服务器.R”
server <- function(input, output){
###create basic plot in ggplot
plotOut <- reactive(
ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point()
)
###display plot
output$plot <- renderPlot({
plotOut()
})
#temp = tempdir() #tried using this in filename to no avail
fName = paste0('plotOut', Sys.Date(), '.png')
##save plot file as png
output$downloadPlot1 <- downloadHandler(
filename = function(){fName},
content = function(file){
ggsave(file,plot=plotOut())
})
##format excel file for output
output$dl_excel <- downloadHandler(
filename = function(){
paste0('results_', Sys.Date(), '.xlsx')
},
content = function(file){
my_workbook <- createWorkbook()
addWorksheet(
wb = my_workbook,
sheetName = "Sheet1"
)
insertImage(my_workbook, sheet = 1,
file = fName
, width = 4, height = 4, startRow = 1, startCol = 1, units = "in", dpi = 300
)
saveWorkbook(my_workbook, file)
}
)
}
另一个论坛中的某人帮助我解决了这个问题。 将代码更新为以下内容可解决此问题。
output$dl_excel <-
downloadHandler(
filename = function() {
paste0('results_', Sys.Date(), '.xlsx')
},
content = function(file) {
**tempPNG <- tempfile(fileext = ".png") #create a tempfile to print the plot to
ggsave(tempPNG, plot = plotOut()) #print the plot to the tempfile**
my_workbook <-
createWorkbook()
addWorksheet(wb = my_workbook,
sheetName = "Sheet1")
insertImage(
my_workbook,
sheet = 1,
**file = tempPNG, #use the tempfile**
width = 4,
height = 4,
startRow = 1,
startCol = 1,
units = "in",
dpi = 300
)
saveWorkbook(my_workbook, file)
}
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.