如何强制Knitr在所有其他代码块之后评估\ Sexpr

时间:2014-06-30 20:23:54

标签: r latex knitr

我正在尝试为动态文档编写摘要,但我的\Sexpr{}调用无效。

基本上我所要做的就是用一个摘要启动文档,该摘要具有从\Sexpr{value}生成的p值,其中值在文档中“下游”确定。例如

这有效:

\begin{document}

<<foo>>=
   value = 10
@

Today I bought \Sexpr{value} Salamanders

\end{document}

这不起作用(以及我想要完成的任务)

\begin{document}

Today I bought \Sexpr{value} Salamanders

<<foo>>=
  value = 10
@

2 个答案:

答案 0 :(得分:3)

在评估代码块之后,我没有看到推迟评估\Sexpr的直接解决方案,但仍然可以轻松地将\Sexp与稍后定义的值一起使用,例如, abstract:对抽象使用单独的文件(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之前处理文档。因此,在&#34;之前,LaTeX命令\input{myabstract}包括myabstract.tex&#34;并不重要。 (不是指时间而是指行号),knit("myabstract.Rnw")生成myabstract.tex

对于更复杂的场景,评估和输出可以分开:在早期块中进行所有计算并将结果打印到它们所属的位置。要显示源代码reuse块(设置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}

答案 1 :(得分:1)

从直观的角度来看,这会引发错误:你怎么能谈论尚未计算的对象的价值?

一种可能的解决方法是先运行代码块但有include=FALSE,然后再重新使用代码块,请参阅Chunk Reference/Macro: How to reuse chunks | knitr

\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}