使用knitr有条件地显示markdown文本块 [英] Conditionally display block of markdown text using knitr

查看:114
本文介绍了使用knitr有条件地显示markdown文本块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编辑一个带有问题"列表的rmarkdown(Rmd)文档,每个问题及其解决方案.每个解决方案都可能包含R控制台的结果,但也包含一些解释性文本(markdown和LaTeX格式).此外,我想将其分为两个版本:有和没有解决方案,尽可能少地更改源代码,然后进行编译.

I would like to edit a single rmarkdown (Rmd) document with a list of "problems", each followed by its solution. Each solution may contain the results of R console, but also some explaining (markdown and LaTeX formatted) text. Besides, I would like to knitr it in 2 versions: with and without the solutions, changing the source as less as possible, and compiling.

我知道我可以使用逻辑变量来有条件地评估R代码并显示图和R输出,但是我不知道如何显示/隐藏(markdown和LaTeX)格式的文本块,除非我将所有将该文本转换成R个字符向量,这似乎很难保持整洁和可读.

I know I can use a logical variable in order to conditionally evaluate R code and show plots and R output, but I don't know how to show/hide blocks of (markdown and LaTeX) formatted text, unless I put all that text into R character vectors, which seems hard in order to keep things clean and readable.

我发现了一个老问题

有条件地在R Markdown中显示文本块

其中给出了针对简单短文本的解决方案,该短文本作为R print()函数的自变量包含在内.

where the solution was given for simple short text, which was included as an argument of the R print() function.

另一个老问题

使用Knitr将Markdown文档的部分插入另一个Markdown文档中

是因为有一个父文件和子文件经过有条件地编译,但是我不想将我的文件切成很多碎片.

was for having a father document and child documents which were conditionally compiled, but I don't want to slice my document into so many pieces.

推荐答案

您可以使用asis引擎有条件地包括/排除 knitr 中的任意文本,例如

You could use the asis engine to conditionally include/exclude arbitrary text in knitr, e.g.

```{asis, echo=FALSE}
Some arbitrary text.

1. item
2. item

Change echo=TRUE or FALSE to display/hide this chunk.
```

但是我刚刚发现了此引擎中的错误,并对其进行了修复.除非您使用 knitr > = 1.11.6,否则您可以自己创建一个简单的asis引擎,例如

But I just discovered a bug in this engine and fixed it. Unless you use knitr >= 1.11.6, you can create a simple asis engine by yourself, e.g.

```{r setup, include=FALSE}
library(knitr)
knit_engines$set(asis = function(options) {
  if (options$echo && options$eval) paste(options$code, collapse = '\n')
})
```

如果要在文本中包含内联R表达式,则必须编织文本,例如

If you want to include inline R expressions in the text, you will have to knit the text, e.g.

```{r setup, include=FALSE}
library(knitr)
knit_engines$set(asis = function(options) {
  if (options$echo && options$eval) knit_child(text = options$code)
})
```

这篇关于使用knitr有条件地显示markdown文本块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆