如何在RMarkdown中合并和打印多个代码块?

4
我的R Markdown文档大致如下。
---
yaml metadata
---

```{r}
x <- 10
```

Some code explanation

```{r}
y <- 10
```

Some more code explanation

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

The final output

```
# 10
```

因为我遵循文学编程的概念,所以如何打印这些多个代码块拼接在一起,以便我可以将整个工作代码打印出来,而不需要代码解释。此外,我能否选择特定的代码块而不是全部并将它们打印出来?

x <- 10
y <- 10
z <- x + y
1个回答

6
一个技巧是使用knitrref.label=""代码块选项(可以使用一个或多个块标签)。这需要您标记您的代码块(至少是您想要重复的代码块)。为了演示,我已经“隐藏”(echo=FALSE)其中一个块,以显示输出可以被偏移(如https://dev59.com/z10a5IYBdhLWcg3whI4b#30243074),尽管它仍然在原地执行。
---
output: md_document
---

```{r block1}
x <- 10
```

Some code explanation, next code block hidden here but still evaluated

```{r block2, echo = FALSE}
y <- 10
```

Some more code explanation

```{r block3}
z <- x + y
```

The final output

```
# 10
```

# Annex 1

Each block individually:

```{r showblock1, ref.label='block1', eval=FALSE}
```
```{r showblock2, ref.label='block2', eval=FALSE}
```
```{r showblock3, ref.label='block3', eval=FALSE}
```


# Annex 2

If you want them more compactly concatenated:

```{r showblocks, ref.label=c('block1','block2','block3'), eval=FALSE}

渲染后将产生这个Markdown文件:
    x <- 10

Some code explanation, next code block hidden here but still evaluated

Some more code explanation

    z <- x + y

The final output

    # 10

Annex 1
=======

Each block individually:

    x <- 10

    y <- 10

    z <- x + y

Annex 2
=======

If you want them more compactly concatenated:

    x <- 10
    y <- 10
    z <- x + y

你可以渲染成任何格式,结果应该是相似的。


1
太好了!这个答案和其他的回答都非常有帮助。 - Shantanu
1
你的问题促使我学习到 ref.label= 可以接受多个参数。每天都要学点新东西。 - r2evans
嘿r2evans,我如何从这样的内容创建一个SQL UNION查询?```{sql block1, ref.label = 'block1', connection = con, eval=FALSE} SELECT TOP 5 * FROM EMPLOYEES_AMERICAS ``` ```{sql block2, ref.label = 'block2', connection = con, eval=FALSE} SELECT TOP 5 * FROM EMPLOYEES_EUROPE ``` ```{sql, ref.label=c('block1','block2'), eval=FALSE} ``` - Shantanu
抱歉格式有些混乱,我无法在此处正确编辑它。我正在尝试弄清楚如何在两个查询之间添加单词“UNION”。 - Shantanu
1
这是两个查询,分别在两个块中。我相信每个查询都会单独发送到SQL服务器,因此如果您想将它们合并,必须在一个查询中执行。无论如何,这与问题无关,我建议您提出一个新问题。 - r2evans

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接