5
votes

In my rmarkdown file, I was wondering whether it was possible to be inside a r chunk and use the fig.cap option value inside the r-chunk itself.

For example:

```{r fig.cap = 'test'}
code
.
.
print(options$fig.cap)?
````

Thanks in advance for any help or advice to where to start looking

2

2 Answers

1
votes

Interesting question. I'd like to know the proper way to do this, but this (very) hacky way works for me.

---
output: 
  html_document:
    css: ~/knitr.css
---

```{r, include=FALSE}
library(knitr)
knit_hooks$set(plot = function(x, options) {
  fig_fn = paste0(opts_knit$get('base.url'), paste(x, collapse = '.'))
  fig.cap <<- knitr:::.img.cap(options)
  sprintf("<figure><img src='%s'><figcaption>%s</figcaption></figure>",
          fig_fn, fig.cap)
  })
```

```{r, fig.cap = 'Figure I: the plot of my figure.'}
plot(1:5)
````

I say some things and some other things.

Oh, yeah please refer to `r fig.cap`

enter image description here

This works for the most recent figure generated, but you could work in a figure counter or something else to make unique variables for each caption so that you can reference whenever you want.

1
votes

It can be retrieved with knitr::opts_current$get("fig.cap"). Here's an example:

```{r fig.cap = 'test'}
library(knitr)
code
.
.
print(opts_current$get("fig.cap"))
````