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

一笑奈何 提交于 2019-12-30 02:11:06

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/15708231/knitr-use-an-inline-expression-in-fig-cap-chunk-option

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!