我可以使用 eval=false 在 r markdown 中生成图形标题吗?
can I produce a figure caption in r markdown with eval=false?
如果我有 MWE:
---
title: "Example"
output:
pdf_document:
fig_caption: yes
---
Text text text
```{r fig.cap="Figure 1. Some random numbers",eval=FALSE}
summary(cars)
```
然后我没有得到标题。但如果我这样做:
---
title: "Example"
output:
pdf_document:
fig_caption: yes
---
Text text text
```{r fig.cap="Figure 1. Some random numbers"}
summary(cars)
```
即删除 eval=FALSE
然后字幕将不再加载。
我为什么要这样做?
我想将示例代码放入我的文档中。该代码实际上不会工作,因此我想禁止它。像
---
title: "Example"
output:
pdf_document:
fig_caption: yes
---
Text text text
```{r fig.cap="Figure 1. Some random numbers",eval=FALSE}
for (i in 1:length(c){
#do something
}
```
我只是在演示一个 for 循环,而不是 运行 代码。
据我所知,knitr 默认不支持代码的标题。标记代码块的最简单方法是在 markdown 中的框下方添加说明。
如果r代码中一定要有说明文字,可以使用chunk hooks。这是您的案例的示例:
---
title: "Example"
output:
pdf_document:
fig_caption: yes
---
```{r}
library(knitr)
knit_hooks$set(wrapper = function(before, options, envir) {
if (!before) {
sprintf(options$comment)
}
})
```
```{r comment="Figure 1. Some random numbers",wrapper=TRUE,eval=FALSE}
for (i in 1:length(c){
#do something
}
```
我们定义了一个钩子 (wrapper
),如果我们在任何块选项中调用 wrapper=TRUE
,comment
参数将在下面打印。
如果我有 MWE:
---
title: "Example"
output:
pdf_document:
fig_caption: yes
---
Text text text
```{r fig.cap="Figure 1. Some random numbers",eval=FALSE}
summary(cars)
```
然后我没有得到标题。但如果我这样做:
---
title: "Example"
output:
pdf_document:
fig_caption: yes
---
Text text text
```{r fig.cap="Figure 1. Some random numbers"}
summary(cars)
```
即删除 eval=FALSE
然后字幕将不再加载。
我为什么要这样做?
我想将示例代码放入我的文档中。该代码实际上不会工作,因此我想禁止它。像
---
title: "Example"
output:
pdf_document:
fig_caption: yes
---
Text text text
```{r fig.cap="Figure 1. Some random numbers",eval=FALSE}
for (i in 1:length(c){
#do something
}
```
我只是在演示一个 for 循环,而不是 运行 代码。
据我所知,knitr 默认不支持代码的标题。标记代码块的最简单方法是在 markdown 中的框下方添加说明。
如果r代码中一定要有说明文字,可以使用chunk hooks。这是您的案例的示例:
---
title: "Example"
output:
pdf_document:
fig_caption: yes
---
```{r}
library(knitr)
knit_hooks$set(wrapper = function(before, options, envir) {
if (!before) {
sprintf(options$comment)
}
})
```
```{r comment="Figure 1. Some random numbers",wrapper=TRUE,eval=FALSE}
for (i in 1:length(c){
#do something
}
```
我们定义了一个钩子 (wrapper
),如果我们在任何块选项中调用 wrapper=TRUE
,comment
参数将在下面打印。