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?
You can insert an R code chunk either using the RStudio toolbar (the Insert button) or the keyboard shortcut Ctrl + Alt + I ( Cmd + Option + I on macOS).
Inline code enables you to insert R code into your document to dynamically updated portions of your text. To insert inline code you need to encompass your R code within: . For example, you could write: Which would render to: The mean sepal length found in the iris data set is 5.8433333.
knitr is an engine for dynamic report generation with R. It is a package in the programming language R that enables integration of R code into LaTeX, LyX, HTML, Markdown, AsciiDoc, and reStructuredText documents. The purpose of knitr is to allow reproducible research in R through the means of literate programming.
If you prefer to use the console by default for all your R Markdown documents (restoring the behavior in previous versions of RStudio), you can make Chunk Output in Console the default: Tools -> Options -> R Markdown -> Show output inline for all R Markdown documents .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With