Reputation: 490
I'm creating a tutorial that involves telling the reader what to put into a file we'll call utils.R
. The user would get the tutorial as an HTML file. Throughout the tutorial utils.R
changes and the Rmd document uses the code in utils.R
as it exists at that stage of the tutorial. During the rendering, I'd like for the code chunks to use source("utils.R")
as it exists at that stage of the tutorial. I'm looking for a way to either...
1. Write the contents of a code chunk to a file. For example...
```{r utils_1}
summary(cars)
median(cars$speed)
```
Is there a way to write the code in utils_1
to a file?
2. Create a nicely formatted code chunk from a text string (I know how to write that to a file). For example...
z <- "summary(cars)\nmedian(cars$speed)"
write(z, "utils.R")
Will generate utils.R
, but is there a way to turn z
into a properly formatted code chunk.
I could create multiple versions of utils.R
and use echo=F
to hide that I'm loading that behind the scenes, but that seems like a pain.
Upvotes: 0
Views: 1133
Reputation: 11
Not sure if this is what are you looking for but you can use child
option to generate them from another file. I use it for automated reports as it helps to keep the main Rmd a bit simpler
```{r child=utils.R}
```
I often place the child code in the YAML though, and call it (matter of tastes I guess...):
---
params:
utils: "utils.R"
---
```{r child=params$utils}
```
Upvotes: 1