简体   繁体   中英

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

If I have the 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.

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.

As far as I know, knitr doesn't support captions for code by default. The easiest way to label your code blocks would be to add an explanation below the box in the markdown.

If you must have captions in the r code, you can use chunk hooks . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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