r - 如何将 Shiny 中生成的 react 图传递给 Rmarkdown 以生成动态报告

标签 r shiny r-markdown report shiny-reactivity

简而言之,我希望能够通过单击按钮从我 Shiny 的应用程序生成动态 Rmarkdown 报告文件(pdf 或 html)。为此,我想我将使用参数化 Report for Shiny。但不知何故,我无法将单个拼图转移到预期的目标:

使用此代码,我们可以在 R Shiny 中生成和下载响应式(Reactive)雷达图:

library(shiny)
library(radarchart)

js <- paste0(c(
  "$(document).ready(function(){",
  "  $('#downloadPlot').on('click', function(){",
  "    var el = document.getElementById('plot1');",
  "    // Clone the chart to add a background color.",
  "    var cloneCanvas = document.createElement('canvas');",
  "    cloneCanvas.width = el.width;",
  "    cloneCanvas.height = el.height;",
  "    var ctx = cloneCanvas.getContext('2d');",
  "    ctx.fillStyle = '#FFFFFF';",
  "    ctx.fillRect(0, 0, el.width, el.height);",
  "    ctx.drawImage(el, 0, 0);",
  "    // Download.",
  "    const a = document.createElement('a');",
  "    document.body.append(a);",
  "    a.download = 'radarchart.png';",
  "    a.href = cloneCanvas.toDataURL('image/png');",
  "    a.click();",
  "    a.remove();",
  "    cloneCanvas.remove();",
  "  });",
  "});"
), collapse = "\n")

ui <- pageWithSidebar(
  headerPanel('Radarchart Shiny Example'),
  sidebarPanel(
    checkboxGroupInput('selectedPeople', 'Who to include', 
                       names(radarchart::skills)[-1], selected="Rich"),
    actionButton('downloadPlot', 'Download Plot'),
    downloadButton('report', 'Generate Report')
  ),
  mainPanel(
    tags$head(tags$script(HTML(js))),
    chartJSRadarOutput("plot1", width = "450", height = "300"), width = 7
  )
)

server <- function(input, output) {
  output$plot1 <- renderChartJSRadar({
    chartJSRadar(skills[, c("Label", input$selectedPeople)], 
                 maxScale = 10, showToolTipLabel=TRUE) 
  })
}
shinyApp(ui, server)

enter image description here

我想做的是实现:生成可下载的报告 https://shiny.rstudio.com/articles/generating-reports.html

本网站的代码如下:

应用.R

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())
        )
      }
    )
  }
)

报告.Rmd

---
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))
```

我已经尝试了很多像这里一样:

How to pass table and plot in Shiny app as parameters to R Markdown?

Shiny: pass a plot variable to Rmarkdown document when generating a downloadable report

但对我而言,无法将我的代码转换为上面提供的示例代码!单击“生成报告”按钮后,所需的输出将如下所示:

enter image description here

最佳答案

基本上,您的问题已经包含了所有构建 block 。我只更新了报告模板以包含绘制雷达图的代码。作为参数,我决定传递过滤后的数据集。在服务器中,我只调整了 params 的规范:

server <- function(input, output) {
  output$plot1 <- renderChartJSRadar({
    chartJSRadar(skills[, c("Label", input$selectedPeople)], 
                 maxScale = 10, showToolTipLabel=TRUE) 
  })
  
  output$report <- downloadHandler(
    filename = "report.html",
    content = function(file) {
      tempReport <- file.path(tempdir(), "report.Rmd")
      file.copy("report.Rmd", tempReport, overwrite = TRUE)
      
      params <- list(scores = skills[, c("Label", input$selectedPeople)])

      rmarkdown::render(tempReport, output_file = file,
                        params = params,
                        envir = new.env(parent = globalenv())
      )
    }
  )
}

报告.Rmd

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

```{r}
chartJSRadar(params$scores, maxScale = 10, showToolTipLabel=TRUE)
```

enter image description here

关于r - 如何将 Shiny 中生成的 react 图传递给 Rmarkdown 以生成动态报告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71719480/

相关文章:

r - big.matrix 文档中不可重现的示例(应用)

amazon-web-services - 须藤: stop: command not found

javascript - R 中 Shiny 的 STRING 交互网络

r - 在 R Markdown PDF 输出中更改绘图图表大小的输出宽度

r - 从 r 中的数据框中删除每第 n 列

在不改变其他词的情况下替换R中的文本

html - Shiny 的 renderText : half italicized, 一半不是吗?

r - 控制数字/舍入作为基本函数中的参数

css - 增加Rmarkdown主题的宽度 'readthedown'

r - 如何使用另一个数据帧的信息更新数据帧列