Reputation: 35
I am currently developping a Shiny app that lets a user import a data set, performs analysis on it and then displays the results. I would like the user to be able to download the R script used to perform the calculations, for reproductibility purposes. In order to do this, I would like to print the imported data set directly into the script, and here's how I was thinking to do it:
library(shiny)
df <- data.frame("time" = c(0,1,2,3), "conc" = c(0,0.1,0.2,0.3))
ui <- fixedPage(
fixedRow(
downloadButton("download_button", label = "Download")
)
)
server <- function(input, output, session){
output$download_button <- downloadHandler(
filename = function(){
paste0("script_", Sys.Date(), ".R")
},
content = function(file) {
writeLines(paste("df <- ", df), file)
}
)
}
shinyApp(ui,server)
The issue is that the result file looks like this:
df <- c(0, 1, 2, 3)
df <- c(0, 0.1, 0.2, 0.3)
And I want it to look like this (or at least something similar):
df <- data.frame("time" = c(0,1,2,3), "conc" = c(0,0.1,0.2,0.3))
Is it even possible?
Thank you for your time.
Upvotes: 2
Views: 113
Reputation: 468
Use the capture.ouput(dput(df))
in the writelines
function
writeLines(paste("df <- ", capture.output(dput(df))), file, sep = "\n")
It will produce this in the Rscript
df <- structure(list(time = c(0, 1, 2, 3), conc = c(0, 0.1, 0.2, 0.3 df <- )), class = "data.frame", row.names = c(NA, -4L))
Upvotes: 3
Reputation: 70633
One solution would be to create a .Rmd rmarkdown script with a header that includes data which would be used in the analysis. This is a small example:
---
title: "title"
output: html_document
date: "`r Sys.Date()`"
params:
input1: NA
input2: NA
---
In the script, you would call the parameters using syntax params$input1
.
On the server side, you would offer the download like so (example adapter from here):
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,
params = list(input1 = mydata1(), input2 = mydata2()),
envir = new.env(parent = globalenv())
)
}
)
Upvotes: 2