当我下载报告时,它始终是PDF版本。我已经分别对每个人进行了测试,他们的工作因此问题来自于切换,但问题是我尝试了一些事情并且没有任何作用我不明白为什么。
这是我的代码:
library(rmarkdown)
ui <- fluidPage(
selectInput("algo", "Selection de l'agorithme utilise pour la simulation:", choice = list("algo1", "algo2")),
radioButtons('format', 'Document format', c('PDF', 'HTML', 'Word'), inline = TRUE),
downloadButton("report", "Generate report")
)
server <- function(input, output, session) {
output$report <- downloadHandler(
filename = switch(input$format,
"Word" = function() {
paste("reportHtml-", Sys.Date(), ".docx", sep="")
},
"PDF" = function() {
paste("reportPDF-", Sys.Date(), ".pdf", sep="")
},
"Word" = function() {
paste("reportHtml-", Sys.Date(), ".html", sep="")
}
),
content = switch(input$format,
"Word" = function(file1) {
report <- file.path("C:/R_sources/test/reportWord.Rmd")
params <- list(n = input$algo)
rmarkdown::render(report, output_file = file1,
params = params,
envir = new.env(parent = globalenv())
)
},
"PDF" = function(file2) {
report <- file.path("C:/R_sources/test/reportPdf.Rmd")
params <- list(n = input$algo)
rmarkdown::render(report, output_file = file2,
params = params,
envir = new.env(parent = globalenv())
)
},
"Word" = function(file3) {
report <- file.path("C:/R_sources/test/reportWord.Rmd")
params <- list(n = input$algo)
rmarkdown::render(report, output_file = file3,
params = params,
envir = new.env(parent = globalenv())
)
}
)
)
}
shinyApp(ui, server)
答案 0 :(得分:0)
来自https://shiny.rstudio.com/reference/shiny/1.0.5/downloadHandler.html,
filename:文件名的字符串...或返回此类字符串的函数。 (可以从此功能使用反应值和功能。)
因此,您应该将函数传递给filename
参数。
代码中发生的事情是downloadHelper
被评估并在加载时运行,此时input$format
设置为&#34; PDF&#34;因为这是初始值。因此,对switch语句进行评估,filename
始终绑定了PDF函数。
您应该做的是设置一个函数,并在其中使用switch语句。同样适用于content
。所以它应该是这样的:
library(rmarkdown)
ui <- fluidPage(
selectInput("algo", "Selection de l'agorithme utilise pour la simulation:", choice = list("algo1", "algo2")),
radioButtons('format', 'Document format', c('PDF', 'HTML', 'Word'), inline = TRUE),
downloadButton("report", "Generate report")
)
server <- function(input, output, session) {
output$report <- downloadHandler(
filename = function() {
switch(input$format,
Word = paste("reportHtml-", Sys.Date(), ".docx", sep=""),
PDF = paste("reportPDF-", Sys.Date(), ".pdf", sep=""),
HTML = paste("reportHtml-", Sys.Date(), ".html", sep="")
)
},
content = function(file) {
switch(input$format,
Word = {
report <- file.path("C:/R_sources/test/reportWord.Rmd")
params <- list(n = input$algo)
rmarkdown::render(report, output_file = file,
params = params,
envir = new.env(parent = globalenv())
)
},
PDF = {
report <- file.path("C:/R_sources/test/reportPdf.Rmd")
params <- list(n = input$algo)
rmarkdown::render(report, output_file = file,
params = params,
envir = new.env(parent = globalenv())
)
},
HTML = {
report <- file.path("C:/R_sources/test/reportHtml.Rmd")
params <- list(n = input$algo)
rmarkdown::render(report, output_file = file,
params = params,
envir = new.env(parent = globalenv())
)
}
)
}
)
}
shinyApp(ui, server)