I am testing on this topic to avoid recalculating in markdown what is calculated in shiny. The code for the shiny app is fine, but I want to make sure that the plot object is passed to rmarkdown.
Any help would be appreciated.
r source code
library(shiny)
library(rmarkdown)
library(ggplot2)
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")
cat("Copying Rmd file to temporary location:", tempReport, "\n")
file_copied <- file.copy("report.Rmd", tempReport, overwrite = TRUE)
cat("File copied:", file_copied, "\n")
#ggplot2객체 생성
cat("Creating plot object\n")
plot_obj <- ggplot(data.frame(x = rnorm(input$slider), y = rnorm(input$slider)), aes(x, y)) +
geom_point() +
ggtitle(paste("random scatter plot (n =", input$slider, ")"))
cat("Plot object created successfully\n")
# Set up parameters to pass to Rmd document
params <- list(n = input$slider)
cat("Parameters set: n =", input$slider, "\n")
# 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).
tryCatch({
rmarkdown::render(tempReport, output_file = file,
params = params,
envir = new.env(parent = globalenv()))
cat("Rmd rendered successfully\n")
}, error = function(e) {
cat("Error in rendering Rmd:", e$message, "\n")
})
}
)
}
shinyApp(ui = ui, server = server)
report.rmd file
title: "Dynamic report"
output: pdf_document
params:
n: NA
plot: NA
# The `params` object is available in the document.
params$n
A plot of params$n
random points.
params$plot
```---
title: "Dynamic report"
output: pdf_document
params:
n: NA
plot: NA
---
```{r}
# The `params` object is available in the document.
params$n
A plot of params$n
random points.
params$plot