Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

knitr - Evaluate inline r code in rmarkdown figure caption

I am using RStudio and knitr to knit .Rmd to .docx

I would like to include inline code in figure captions e.g. something like the following in the chunk options:

fig.cap = "Graph of nrow(data) data points"

However, knitr does not evaluate this code, instead just printing the unevaluated command.

Is there a way to get knitr to evaluate r code in figure/table captions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

knitr evaluates chunk options as R code. Therefore, to include a variable value in a figure caption, just compose the required string using paste or sprintf:

fig.cap = paste("Graph of", nrow(data), "data points")

Note that this might be problematic if data is created inside this chunk (and not in a previous chunk) because by default chunk options are evaluated before the chunk itself is evaluated.

To solve this issue, use the package option eval.after to have the option fig.cap be evaluated after the chunk itself has been evaluated:

library(knitr)
opts_knit$set(eval.after = "fig.cap")

Here a complete example:

---
title: "SO"
output: 
  word_document: 
    fig_caption: yes
---


```{r fig.cap = paste("Graph of", nrow(iris), "data points.")}
plot(iris)
```


```{r setup}
library(knitr)
opts_knit$set(eval.after = "fig.cap")
```

```{r fig.cap = paste("Graph of", nrow(data2), "data points.")}
data2 <- data.frame(1:10)
plot(data2)
```

The first figure caption works even without eval.after because the iris dataset is always available (as long as datasets has been attached). Generating the second figure caption would fail without eval.after because data2 does not exist before the last chunk has been evaluated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...