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

500 Views Asked by At

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.

2

There are 2 best solutions below

1
Yihui Xie On BEST ANSWER

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')
```
1
MGP On

You need to write the code in the temp.R file, in such a way, that it can directly be evaluated in the chunk.

So for tmp.R use:

cat("# header \n\n")
cat(4+3)

Then you can include this in the R-Markdown file with:

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