[英]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.