I have an .Rmd file which contains commands to build a plot.
buildConstellation.Rmd (see here).
I typically refer to this file from another .Rmd file, which acts as a notebook for a specific dataset or analysis I may be doing at a given time, i.e.,
Usually, I just call
rmarkdown::render and specify the objects that buildConstellation.Rmd takes as
rmarkdown::render(input = './buildConstellation.Rmd', params = list(my_object = neocortex, out.dir = '../out'))
This works fine because the script
buildConstellation.Rmd writes a PDF with the final plot, and all the intermediate tables that it creates are saved to my global environment.
However, I recently had to do a variation of this, where I need to split the object I pass as argument to
neocortex) into three parts, based on a variable
neocortex_split_stages <- neocortex %>% split(.$stage)
Once it is split, I can run
buildConstellation.Rmd on each of the three subsets of the original object.
neocortex_split_stages$early neocortex_split_stages$mid neocortex_split_stages$late
Now, when I pass the newly created list to
map, the intermediate tables don't make it to the .GlobalEnv.
split_stages %>% map(~ rmarkdown::render(input = './buildConstellation.Rmd', params = list(my_object = . , out.dir = '../out'))
The final plots get created, but the only way I can recover the intermediate objects is to write them to a file in
buildConstellation.Rmd, and then import them back in my .GlobalEnv.
I turned the entirety of
buildConstellation.Rmd into a function and saved in a file called
buildConstellation.R, which I can
source and call, and which returns those intermediate objects.
source("../R/buildConstellation.R") constellation_result <- split_stages %>% map(~ buildConstellation(my_object = . , out.dir = '../out' ))
This works, but is ugly. I really would like to know how I can do this using the R markdown file, without having to glob all those pretty chunks and readable text in between into a gross function filled with comments and no chunks.
Your help is greatly appreciated!