包含来自外部 R 脚本的代码 运行 中,同时显示代码和输出

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

是否可以在 .Rmd 中包含来自外部 R 脚本的代码,同时 运行 代码,显示代码,并在输出 .HTML 文件中显示其结果?例如,如果我有

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

external.R 中。在输出文档中,我想看到上面的代码以及 z 的结果,即 4。本质上,我想要相当于如果我 copy/pasted 上面的 R 块中的内容会发生什么。所以我要

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

相当于

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

在输出HTML文件中。 我已经尝试过 knitr::read_chunk('external.R)source('external.R)` 之类的方法,但它们不显示代码。我错过了一些简单的东西吗?


编辑

我发现 source('external.R', echo = TRUE) 会产生我所要求的结果,但是显示的输出的每一行 code/results 前面都有 ##。如果代码只是 copy/pasted 在 .Rmd?

中的一个块中,有什么办法让它看起来像

您可以在代码块选项中设置 comment = NA

示例:

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

这会产生

还有另一种方法,所以它看起来完全就像在 markdown 文件中包含代码。

您的 external.R 文件:

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

您的 Rmarkdown 文件:

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

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

```{r}
<<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 codeexternal.R的内容设置为块代码:

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