![](/img/trans.png)
[英]Is there a way in knitr to evaluate inline code chunks of other languages?
[英]How to force Knitr to evaluate \Sexpr after all other code chunks
我正在尝试为动态文档编写摘要,但是我的\\Sexpr{}
调用不起作用。
从本质上讲,我要做的就是从具有\\Sexpr{value}
生成的p值的摘要开始文档,其中value是在文档中“下游”确定的。 例如
这有效:
\begin{document}
<<foo>>=
value = 10
@
Today I bought \Sexpr{value} Salamanders
\end{document}
这不起作用(以及我要完成的工作)
\begin{document}
Today I bought \Sexpr{value} Salamanders
<<foo>>=
value = 10
@
我看不出有一个直接的解决方案可以在评估代码块之后推迟对\\Sexpr
评估,但是仍然可以很容易地将\\Sexp
与稍后在例如摘要中定义的值一起使用:使用单独的文件( myabstract.Rnw
)对于摘要,在主文档的末尾添加\\input{myabstract}
(应该包含摘要)并knit
myabstract.Rnw
:
document.Rnw
:
\documentclass{article}
\begin{document}
\begin{abstract}
\input{myabstract}
\end{abstract}
Main text.
<<>>=
answer <- 42
@
\end{document}
<<include = FALSE>>=
knit("myabstract.Rnw")
@
myabstract.Rnw
:
The answer is \Sexpr{answer}.
理解它如何工作的关键是要意识到knitr
在LaTeX之前先处理文档。 因此,LaTeX命令\\input{myabstract}
包括myabstract.tex
“ before”(不是指时间,而是指行号), knit("myabstract.Rnw")
生成myabstract.tex
。
对于更复杂的方案,可以将评估和输出分开:尽早进行所有计算并在其所属位置打印结果。 要显示源代码,请重用块(设置eval = FALSE
)。 使用上面的示例,这意味着:
\documentclass{article}
\begin{document}
<<calculation, include = FALSE>>=
answer <- 42
@
\begin{abstract}
The answer is \Sexpr{answer}.
\end{abstract}
Main text.
<<calculation, eval = FALSE>>=
@
\end{document}
从直观的角度来看,这会引发错误是有道理的:您如何谈论尚未计算的对象的值?
可能的解决方法是先运行代码块,但先include=FALSE
,然后再使用代码块,请参见块参考/宏:如何重用代码块| 针织衫
\begin{document}
%%# Code is evaluated but nothing is written in the output
<<foo, include=FALSE>>=
value = 10
plot(sin)
rnorm(5)
@
Today I bought \Sexpr{value} Salamanders
%%# Here code can be included in the output (figure, echo, results etc.)
<<bar>>=
<<foo>>
@
\end{document}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.