I have a workflow with Rmarkdown
and render
that feels far from optimal. Here is what I am currently doing.
I have an .R
script that may have several hundred lines of code already and several dozen objects in my environment. Near or at the end of the script, I'd like to utilize render
to generate some HTML output using objects in my current environment. To accomplish this, I save the objects of interest and re-load them in the script that I pass to render
all while being careful about working directories and where items are located relative to the script I will use to render the html document.
Here is a reproducible example of my current workflow and an example of what I'd like to do.
# Imagine I have a local data.frame/object I am interested in plotting to html via render
iris_revised <- iris
# My current workflow is to save this object
save(iris_revised, file = 'data/iris_revised.Rdata')
# And then call another script via the render function
rmarkdown::render('R/plot_iris_revised.R', output_format = 'html_document')
Where R/plot_iris_revised.R
contains the following code.
library(ggplot2)
load('../data/iris_revised.Rdata')
for(Species in levels(iris_revised$Species)){
cat('#', Species, '\n')
p <- ggplot(iris_revised[iris_revised$Species == Species,], aes(x =
Sepal.Length, y = Sepal.Width)) +
geom_point()
print(p)
}
Ideally instead of the additional overhead of calling a different script, I'd be able to user render
directly at the end of my current script, something akin to the code below (which obviously does not work).
# Ideally I could just do something like this, where I could just render html in the same workflow
input_text <- "
for(Species in levels(iris_revised$Species)){
cat('#', Species, '\n')
p <- ggplot(iris_revised[iris_revised$Species == Species,], aes(x =
Sepal.Length, y = Sepal.Width)) +
geom_point()
print(p)
}
"
rmarkdown::render(input_text, output_format = 'html_document')
I am looking for a solution without changing the original .R
to .Rmd
or an R notebook.
Aside from the ideal capability I present above, I am open to general workflow suggestions of how to easily render some Rmarkdown output at the end of an .R
script.
Since the input
argument refers to an input file, you can just write input_text
to a (possibly temporary) file:
tmp <- tempfile(fileext = ".R")
cat(input_text, file = tmp)
rmarkdown::render(tmp, output_format = "html_document", output_dir = getwd())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With