如何在 RMarkdown 中合并和打印多个代码块? [英] How to merge and print multiple code chunks in RMarkdown?
问题描述
我的 Rmarkdown 文档看起来像这样.
My Rmarkdown document looks something like this.
---
yaml metadata
---
```{r}
x <- 10
```
Some code explanation
```{r}
y <- 10
```
Some more code explanation
```{r}
z <- x + y
```
The final output
```
# 10
```
由于我遵循了文学编程的概念,如何打印这些拼接在一起的多个代码块,所以我可以在没有代码解释的情况下打印出整个工作代码如下.另外,我可以选择特定的代码块而不是全部并将它们打印出来吗?
Since I am following the concepts of literate programming, how to print these multiple code chunks stitched together, so I can get the whole working code printed out as follows without the code explanation. Also, can I select specific code chunks and not all and print them out?
x <- 10
y <- 10
z <- x + y
推荐答案
一个技巧是使用 knitr
的 ref.label=""
块选项(它需要一个或多个块标签).它要求您标记您的块(至少是您想要重复的块).为了演示,我已经隐藏"(echo=FALSE
)块之一以显示输出可以被偏移(如 https://stackoverflow.com/a/30243074/3358272) 虽然它仍然就地执行.
A trick is to use knitr
's ref.label=""
chunk option (which takes one or more block labels). It requires that you label your chunks (at least the ones you want to repeat). For demonstration, I've "hidden" (echo=FALSE
) one of the blocks to show that the output can be offset (as in https://stackoverflow.com/a/30243074/3358272) though it is still executed in-place.
---
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 文件:
Produces this markdown file when rendered:
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
你可以渲染成你想要的任何格式,结果应该是相似的.
You can render into whatever format you want, the results should be similar.
这篇关于如何在 RMarkdown 中合并和打印多个代码块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!