3

I'm trying to download report form shiny app using R Markdown, but I'm lost! I need to pass a plot from shiny as parameter to R Markdown, and then, include this plot in my report. I searched a lot about this, but I couldn't find anything. How can I plot this in my report?

Server.R

lm_dif_filter <- reactive({
    lm_dif_corn[(lm_dif_corn$farmer == input$farmer) & (lm_dif_corn$Treat_X == 'Farmer'),]
  })

output$difPlot <- renderPlotly({
      dif <- ggplot(data=lm_dif_filter(), aes(x=Treat_Y, y=dif)) +
             geom_bar(stat="identity",color = 'black', position=position_dodge(), width = 0.7)+
             geom_hline(yintercept = 0) + 
             #annotate("text", min(Treat_Y), 0, vjust = -1, label = "Farmer")+
             theme(legend.position = "none") +
             labs(x = "Treats", y = "Diff")

      ggplotly(dif)

To download:

output$report <- downloadHandler(
     filename = "report.pdf",
     content = function(file) {
       tempReport <- file.path(tempdir(), "report.Rmd")
       file.copy("report.Rmd", tempReport, overwrite = TRUE)

       # Set up parameters to pass to Rmd document
       params <- list(set_subtitle = input$farmer, plot =  output$difPlot)
       rmarkdown::render(tempReport, output_file = file,
                         params = params,
                         envir = new.env(parent = globalenv())
       )
     }
   )

My report.rmd

---
title: "Some title"
params:
 set_subtitle: test
 plot: NA
subtitle: "`r params$set_subtitle`"
date: '`r format(Sys.Date(), "%B %d, %Y")`'

output:
  pdf_document:
    toc: yes 
header-includes:
    - \usepackage{fancyhdr}
always_allow_html: yes
---
\addtolength{\headheight}{1.0cm} 
\pagestyle{fancyplain} 
\lhead{\includegraphics[height=1.2cm]{bg.png}} 
\renewcommand{\headrulewidth}{0pt} 


```{r, include=FALSE}
options(tinytex.verbose = TRUE)
knitr::opts_chunk$set(echo = FALSE)
cat(params$plot)

  • 1
    If someone answers and that answer solves Your problem then you should upvote by clicking the upward triangle and accept the answer by clicking the gray check mark next to the answer. This is the way to say thank you in stack overflow. Since you are new to this website you should be knowing that. – Sheldore Apr 26 '19 at 00:00
  • When I did this question, my reputation was less than 15, so I was not able to vote and score as a response before. But now I've done it. Thanks for reminding me. – Larissa Teixeira Apr 26 '19 at 00:09

1 Answers1

2

One easy option is to not pass the plot, and instead pass the parameter, and refer to a shared plot function used by the shiny app and Rmd doc. For example,

Shiny app,

note the source("util.R") and report_hist(params$n)



source("util.R")
library(shiny)
shinyApp(
  ui = fluidPage(
    sliderInput("slider", "Slider", 1, 100, 50),
    downloadButton("report", "Generate report"),
    plotOutput("report_hist")
  ),
  server = function(input, output) {
    output$report_hist <- renderPlot({
      report_hist(n = input$slider)
    })
    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 report,

note the report_hist(params$n)

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

report_hist(params$n) #note this function was created in util.R and loaded by the shiny app. 

```

Shared function in util.R

report_hist <- function(n){
  hist(rnorm(n))
}

Here's a demo shiny app you can test it out with, https://rstudio.cloud/project/295626

EconomiCurtis
  • 1,988
  • 4
  • 21
  • 31