knitr:在fig.cap块选项中使用内联表达式

Zan*_*ith 10 knitr

我的问题是关于knitr选项fig.cap,当使用LaTeX时.是否可以在fig.cap字符串中包含\ rinline或\ Sexpr?

例如,我想有类似的东西(我正在使用.Rtex文件):

\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}
Run Code Online (Sandbox Code Playgroud)

我真的很喜欢这个块在我的.tex文档中生成一个情节,标题为"x为5".相反,它会在pdflatex编译时抛出"未定义的控制序列"错误.

如果我没有逃脱rinline(即只使用\ rinline {x}),那么它会编译,但标题是"x islinex".

我问的可能吗?

这是我的第一个SO问题(虽然在这里多次使用答案.谢谢!),所以我很感激有关如何提出更好问题的任何反馈.

谢谢您的帮助!

Bri*_*ggs 8

fig.cap被评估为R表达式,因此您可以在R中创建标题字符串,而不是使用\rinline(因此再次使用标题解析knitr).

%% begin.rcode fig.cap=paste("x is", x)
Run Code Online (Sandbox Code Playgroud)

但是因为默认情况下创建之前fig.cap进行评估,您需要推迟评估; 要做到这一点,你可以在文档的开头包含这样的块: xfig.cap

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

它指定fig.cap在评估代码块之后进行评估,即何时x可以在图标题中使用.请参阅eval.after文档.

另一种方式来做到这一点是建立x以前的块,并使用fig.cap=paste("x is", x)下一大块.