0
votes

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.

1
Could you include some minimal code? I am failing to completely understand what you are trying to achieve. Will the user be interacting with this file within RStudio chunk by chunk, or are you wanting them to knitr the whole document and view the output?Michael Harper
This should help with the second part:stackoverflow.com/q/38818492/7347699Michael Harper
You still need to post complete code. It's not clear what code will do the writing to a file. So post a complete example showing what you want the final result to look like, even if it doesn't work, and someone will be able to fix it to get it to work.user2554330
For interactive stuff, consider using a Jupyter notebook instead of an Rmd file.Hong Ooi

1 Answers

1
votes

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}
```