从Shiny本地保存rmarkdown输出

时间:2018-04-11 19:55:59

标签: r shiny

我有一个闪亮的应用程序,使用rmarkdown生成可下载的报告,工作正常。每当用户上传数据以生成报告时,我希望将报告的副本保存在闪亮的主机上。理想情况下,我希望在downloadHandler调用中执行此操作,以便我不必生成两次报告。

一个最小的例子(改编自this shiny article):

library(shiny)

shinyApp(
  ui = fluidPage(
    sliderInput("slider", "Slider", 1, 100, 50),
    downloadButton("report", "Generate report")
  ),
  server = function(input, output) {
    output$report <- downloadHandler(
      # For PDF output, change this to "report.pdf"
      filename = "report.html",
      content = function(file) {
        # Copy the report file to a temporary directory before processing it, in
        # case we don't have write permissions to the current working dir (which
        # can happen when deployed).
        tempReport <- file.path(tempdir(), "report.Rmd")
        file.copy("report.Rmd", tempReport, overwrite = TRUE)

        # Set up parameters to pass to Rmd document
        params <- list(n = input$slider)

        # Knit the document, passing in the `params` list, and eval it in a
        # child of the global environment (this isolates the code in the document
        # from the code in this app).
        rmarkdown::render(tempReport, output_file = file,
                          params = params,
                          envir = new.env(parent = globalenv())
        )
      }
    )
  }
)

rmarkdown文件

---
title: "Dynamic report"
output: html_document
params:
  n: NA
---

  ```{r}
# The `params` object is available in the document.
params$n
```

A plot of `params$n` random points.

```{r}
plot(rnorm(params$n), rnorm(params$n))
```

1 个答案:

答案 0 :(得分:1)

您基本上只需要将生成的报告复制到另一个目录中。以下是基于您提供的代码的示例。

library(shiny)

if(!dir.exists("reportDir"))
   dir.create("reportDir")

shinyApp(
  ui = fluidPage(
    sliderInput("slider", "Slider", 1, 100, 50),
    downloadButton("report", "Generate report")
  ),
  server = function(input, output) {
    output$report <- downloadHandler(
      # For PDF output, change this to "report.pdf"
      filename = "report.html",
      content = function(file) {
        # Copy the report file to a temporary directory before processing it, in
        # case we don't have write permissions to the current working dir (which
        # can happen when deployed).
        tempReport <- file.path(tempdir(), "report.Rmd")
        file.copy("report.Rmd", tempReport, overwrite = TRUE)

        # Set up parameters to pass to Rmd document
        params <- list(n = input$slider)

        # Knit the document, passing in the `params` list, and eval it in a
        # child of the global environment (this isolates the code in the document
        # from the code in this app).
        rmarkdown::render(tempReport, output_file = file,
                          params = params,
                          envir = new.env(parent = globalenv())
        )

        # copy generated report
        file.copy(file, paste("reportDir/", Sys.time(), ".html"))
      }
    )
  }
)