Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knitr: Use an inline expression in fig.cap chunk option

Tags:

knitr

My question is about the knitr option fig.cap, when using LaTeX. Is it possible to include an \rinline or \Sexpr in the fig.cap character string?

For example, I would like to have something like (I'm using an .Rtex file):

\documentclass{article}
\begin{document}
%% begin.rcode fig.cap="x is \\rinline{x}"
% x <- 5
% p <- seq(0,5)
% q <- x*p
% plot(p,q)
%% end.rcode
\end{document}

I'd really like for that chunk to produce a plot in my .tex document, with a caption reading "x is 5". Instead, it throws an "undefined control sequence" error on pdflatex compilation.

If I don't escape the rinline (i.e. use just \rinline{x}), then it compiles, but the caption is "x is inlinex".

Is what I'm asking possible?

This is my first SO question (used the answers here many times, though. Thanks!), so I'd appreciate any feedback on how to ask better questions.

Thanks for the help!

like image 921
Zane Beckwith Avatar asked Mar 29 '13 17:03

Zane Beckwith


1 Answers

fig.cap is evaluated as an R expression, so instead of using \rinline (and thus having the caption again parsed by knitr), you can just create the caption string in R.

%% begin.rcode fig.cap=paste("x is", x)

but because fig.cap is evaluated before x is created by default, you will need to postpone the evaluation of fig.cap; to do that, you can include a chunk like this in the beginning of your document:

%% begin.rcode setup, include=FALSE
%% opts_knit$set(eval.after = 'fig.cap')
%% end.rcode

It specifies fig.cap to be evaluated after the code chunk is evaluated, i.e. when x is available for you to use in the figure caption. See eval.after in the documentation.

The other way to do this is to create x in a previous chunk, and use fig.cap=paste("x is", x) in the next chunk.

like image 148
Brian Diggs Avatar answered Jan 01 '23 21:01

Brian Diggs