Reputation: 1866
I have created a Shiny app, which involves the user importing data, manipulating it, creating a datatable and associated plot.
I'd like to build in a downloadable report using Rmarkdown (which I've only just started to use). However, i am unsure how to print the datatables and plots generated in R, in the Rmarkdown script, without copying the whole R code from the Shiny app. It is quite a long piece of code, so i'd like to be able to use the outputs directly.
As an example, I've copied the following app to demonstrate my point.
library(shiny)
ui <- fluidPage(
titlePanel("Old Faithful Geyser Data"),
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)
),
mainPanel(
plotOutput("distPlot"),
dataTableOutput("summary_table"),
downloadButton("report", "Generate report")
)
)
)
server <- function(input, output) {
output$distPlot <- renderPlot({
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
output$summary_table <- renderDataTable({
x <- faithful
head(x,5)
})
output$report <- downloadHandler(
filename = "report.html",
content = function(file) {
tempReport <- file.path(tempdir(), "report.Rmd")
file.copy("report.Rmd", tempReport, overwrite = TRUE)
rmarkdown::render(tempReport, output_file = file,
envir = new.env(parent = globalenv())
)
}
)
}
shinyApp(ui = ui, server = server)
I would like to access the plot and data table in my downloadable R markdown file.
Upvotes: 0
Views: 1552
Reputation: 27732
my approach, using app.R and test.Rmd
in app.R create a reactive variable, containing the plot/chart (replace with your own plot).
chart1 <- reactive({
ggmap(get_map(location = "Netherlands",
zoom = 7,
scale = 2,
color="bw",
language = "nl-NL"))
})
then, call the markdown:
output$report <- downloadHandler(
filename = "test.pdf",
content = function(file) {
src <- normalizePath('test.Rmd')
#switch to system tempdir
#just in case the app doesn't have write persission in the current folder
owd <- setwd(tempdir())
on.exit(setwd(owd))
file.copy(src, 'test.Rmd', overwrite = TRUE)
out <- render("test.Rmd", "pdf_document" )
file.rename(out, file)
}
)
in the .Rmd file, you then can call on the chart:
plot(chart1())
Note the () after chart1!!!
Follow the same structure for tables, an all other objects you wish to include in your markdown..
Upvotes: 1