Here's how I did it:
I first added some hooks in the Rmd document where I wanted to drop the script:
---
title: "Insert R as Code Chunk"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
{{AnalysisStart}}
{{AnalysisEnd}}
I then wrote a function that reads in my script and does a find and replace for the hooks within the .Rmd file
write_to_rmd <- function(script, rmd, hook, output_path){
#Read in script
source <- readr::read_file(script)
#Concatenate Rmd chunk yml
source <- paste0("```{r, eval = F}\n",source, "```")
#Read in Rmd
rmd <- readr::read_file(rmd)
#Get mustache regex in chapter .Rmd files
header_regex <- sprintf("\\{\\{%sStart\\}\\}(.*?)\\{\\{%sEnd\\}\\}",
hook,
hook)
#Do a gsub to replace hooks with script text
output <- gsub(header_regex, source, rmd)
#write output to file
readr::write_file(output, path = output_path)
}
The function output (written to output_path) looks like
---
title: "Insert R as Code Chunk"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
plot(rnorm(100))
```