Tom
Tom

Reputation: 1138

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.

Upvotes: 2

Views: 703

Answers (2)

Yihui Xie
Yihui Xie

Reputation: 30174

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')
```

Upvotes: 3

MGP
MGP

Reputation: 2551

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")
```

Upvotes: 1

Related Questions