rr-markdownmarkdownknitrknitr-spin

Include R script with markdown tags as external file in Rmarkdown file


suppose I have an .R file tmp.R with markdown tags, e.g.

#' # header    
5+1

and I want to include that into a (much larger) .Rmd file as external source. R code and markdown tags shall be evaluated as if it were rendered directly. How I would do that?

---
title: "Untitled"
output: html_document
---

I played around with several options, including

```{r, results='asis'}
source("tmp.R")
```

or

```{r, results='asis'}
knitr::spin("tmp.R')
```

and several others. Unfortunately I didn't find a solution on stackoverflow, including this, this, this, this or this question.


Solution

  • I'm not totally sure if I understand your question, but it sounds to me that you were looking for knitr::spin_child(), which converts an R script to Rmd and knit it as a child document:

    ```{r}
    knitr::spin_child('tmp.R')
    ```