Hello,
I am writing a report in R Markdown which will contain one section (out of many). This one section, in turn, will contain many sub-sections (> 20). Each of these sub-sections will contain mainly text. In order to dynamically control whether one or more of these sub-sections is included in the final report, my intention is to include all of these sub-sections through "child" .Rmd files, and controlling their inclusion (or not) through code chunks and the eval
option in the main .Rmd file (how this is achieved is not relevant for the question at hand), like so:
```{r child = '[name].Rmd', eval = TRUE}
```
Where [name].Rmd
is the relevant "child" .Rmd file containing the text pertaining to the sub-section it is included under.
Since there are many sub-sections there is a need for equally many "child" .Rmd files. Instead of creating and naming these "child" .Rmd files manually, I am looking for a solution whereby I can generate these "child" .Rmd files after looping through a data frame of names and output these .Rmd files to a relevant location on my drive.
Let's say I have a data frame with the following names.
library(tidyverse)
library(rmarkdown)
names <- tibble(
name = c("name_one", "name_two")
)
What I want to achieve (or at least what I envision) is something that loops through each of these names, and outputs an .Rmd for each of the names (for the example above, that would be two files: name_one.Rmd
and name_two.Rmd
). The contents of each "child" .Rmd file thus output should be blank/containing the bare minimum necessary, since these will mainly contain text that I have to input manually (unfortunately). I have tried achieving this using the rmarkdown::render
function, as such (the template.Rmd
is the "blank" .Rmd file I am basing the "children" on):
for (i in 1:length(names$name)) {
render("template.Rmd",
output_file = paste0(names$name, ".Rmd"),
output_dir = here::here()))
}
This outputs the relevant .Rmd files, but these are not possible to open and contain (what is to me) jibberish - which I suspect has something to do with the intention of the rmarkdown::render
function is to output HTML, PDF or Word files.
Is there anyone out there that has a suggestion on how I can achieve my goal? Any nudges in the right direction would be greatly appreciated!
Thanks for a great community.
Rikard