When trying to knit
an .Rmd containing read_chunk
lines from purl
scripts into a parent .Rmd, the chunks are not complete and only form code blocks. I want to be able to knit
the output file normally.
main.Rmd
---
output: html_document
---
```{r, include=FALSE}
knitr::read_chunk("script_chunk.R")
```
### Print sessionInfo()
```{r, ref.label='script_chunk', eval=FALSE}
```
script_chunk.R
# ---- script_chunk
sessionInfo()
When I process this with knit("main.Rmd", "output.Rmd")
the following file is generated:
---
output: html_document
---
### Print sessionInfo()
```r
sessionInfo()
```
However, the desired output for the chunk is:
```{r script_chunk}
sessionInfo()
```
When I knit
output.Rmd currently, I only get an un-evaluated code block because the chunk is missing the curly braces (and preferably the chunk name).
I can use readLines
to achieve what I'm after, for example with:
```{r, results='asis', collapse=TRUE, echo=FALSE}
cat("```{r script_chunk}\n")
cat(paste(readLines("script_chunk.R"), "\n", collapse = ""))
cat("```\n")
```
Is there a more elegant way to do this?
There is a slightly more elegant solution:
# main.Rmd
---
output: html_document
---
### Print sessionInfo()
```{r, results="asis", echo = FALSE}
chunk_lines <- knitr::spin(text = readLines("script_chunk.R"), knit = FALSE)
cat(chunk_lines, sep = "\n")
```
But remember that your output, as far as knitr
cares, is plain Markdown. knitr
can only output to certain formats: LaTeX, Sweave, HTML, Markdown or Jekyll. While your output file has the .Rmd
extension, its contents are plain Markdown because that's the default for R Markdown files.
So be aware that all code chunks you want in the output will have to be written as dynamic output. Which could leave you with obfuscated code in main.Rmd
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With