Include code from an external R script, run in, display both code and output

帅比萌擦擦* 提交于 2019-12-04 00:26:06

Although the accepted answer provides a simple and working solution, I think the most idiomatic way of doing this (without having to modify the external script at all) is to use the chunk option code to set the contents of external.R as chunk code:

```{r, code = readLines("external.R")}
```

There is another way of doing it so it looks exactly like having the code in the markdown file.

Your external.R file:

## @knitr answer
x <- 1
y <- 3
z <- x + y
z

Your Rmarkdown file:

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

```{r echo=FALSE}
knitr::read_chunk('external.R')
```

```{r}
<<answer>>
```

That produces:

You could set comment = NA in your code chunk options.

Example:

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

```{r setup, include=FALSE}
knitr::opts_chunk$set(
    echo = TRUE,
    comment=NA)
```

## Example

```{r}
source("example.R", echo = T, prompt.echo = "", spaced = F)
```

This produces

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!