首页 > 解决方案 > Include code from an external R script, run in, display both code and output

问题描述

Is it possible to include code from an external R script in an .Rmd and simultaneously run the code, display the code, and display its results in the output .HTML file? For example, if I have

x <- 1
y <- 3
z <- x + y
z

in external.R. In the output document I want to see the code above along with the result of z, i.e. 4. Essentially, I want the equivalent of what would happen if I copy/pasted what's above in an R chunk. So I want

```{r}
some.library::some.function("external.R")
```

to be the equivalent of

```{r}
x <- 1
y <- 3
z <- x + y
z
```

In the output HTML file. I've tried things like knitr::read_chunk('external.R) and source('external.R)`, but these don't display the code. Am I missing something simple?


EDIT

I found that source('external.R', echo = TRUE) will produce what I ask, but each line of the output's displayed code/results is prepended by ##. Any way to make it look like it would if the code was simply copy/pasted in a chunk in the .Rmd?

标签: rr-markdownknitr

解决方案


尽管接受的答案提供了一个简单且有效的解决方案,但我认为最惯用的方法(根本不必修改外部脚本)是使用块选项code将内容设置external.R为块代码:

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

推荐阅读