在rmarkdown图形标题中评估内联r代码 [英] Evaluate inline r code in rmarkdown figure caption
问题描述
我正在使用RStudio和knitr来编织.Rmd到.docx
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 ="nrow(data)
个数据点的图形"
fig.cap = "Graph of nrow(data)
data points"
但是,knitr不会评估该代码,而只是打印未评估的命令.
However, knitr does not evaluate this code, instead just printing the unevaluated command.
有没有办法让knitr在图形/表格标题中评估r代码?
Is there a way to get knitr to evaluate r code in figure/table captions?
推荐答案
knitr
将块选项评估为R代码.因此,要在图形标题中包含变量值,只需使用paste
或sprintf
组成所需的字符串:
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")
请注意,如果在 块内(而不是在先前的块中)创建data
,则可能会出现问题,因为默认情况下,在 块之前对块选项进行评估本身进行评估.
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.
要解决此问题,请使用软件包选项 eval.after
使选项fig.cap
在评估块本身之后对其进行评估:
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)
```
即使没有eval.after
,第一个图形标题也可以使用,因为iris
数据集始终可用(只要已附加datasets
).如果没有eval.after
,则生成第二个图形标题将失败,因为在评估最后一个块之前不存在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.
这篇关于在rmarkdown图形标题中评估内联r代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!