简体   繁体   English

我可以在带有eval = false的r markdown中产生图形标题吗?

[英]can I produce a figure caption in r markdown with eval=false?

If I have the MWE: 如果我拥有MWE:

---

title: "Example"
output:
  pdf_document:
    fig_caption: yes

---


Text text text


```{r fig.cap="Figure 1. Some random numbers",eval=FALSE}
summary(cars) 
```

then I do not get a caption. 那么我就没有标题。 But if I do: 但是,如果我这样做:

---
title: "Example"
output:
  pdf_document:
    fig_caption: yes
---


Text text text


```{r fig.cap="Figure 1. Some random numbers"}
summary(cars) 
```

ie remove eval=FALSE then the caption no longer loads. 即删除eval=FALSE则说明字幕不再加载。

why I wish to do this? 为什么我要这样做?

I want to put example bits of code into my document. 我想将示例代码片段放入我的文档中。 the code won't actually work, hence why I want to supress it. 该代码实际上将无法正常工作,因此为什么我要抑制它。 Something like 就像是

---

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

where I am merely demonstrating a for loop, but not actually running the code. 我只是在演示一个for循环,而没有实际运行代码。

As far as I know, knitr doesn't support captions for code by default. 据我所知,knitr默认情况下不支持代码标题。 The easiest way to label your code blocks would be to add an explanation below the box in the markdown. 标记代码块的最简单方法是在markdown框下方添加说明。

If you must have captions in the r code, you can use chunk hooks . 如果必须在r代码中包含标题,则可以使用块挂钩 Here's an example for your case: 这是您的情况的示例:

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

We have defined a hook ( wrapper ), where if we call wrapper=TRUE in any chunk options, the comment argument is printed below. 我们定义了一个钩子( wrapper ),如果我们在任何块选项中调用wrapper=TRUE ,则comment参数将显示在下面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM