How to force Knitr to evaluate \Sexpr after all other code chunks

与世无争的帅哥 提交于 2019-12-23 10:20:26

问题


I am trying to write an abstract for a dynamic document, but my \Sexpr{} calls are not working.

Essentially all I am trying to do is start the document off with an abstract that has p-values generated from \Sexpr{value} where value is determined "downstream" in the document. For example

This works:

\begin{document}

<<foo>>=
   value = 10
@

Today I bought \Sexpr{value} Salamanders

\end{document}

This does not work (and what I am trying to accomplish)

\begin{document}

Today I bought \Sexpr{value} Salamanders

<<foo>>=
  value = 10
@

回答1:


I don't see a straightforward solution to postpone evaluation of \Sexpr after evaluation of code chunks, but it is still easy to use \Sexp with values defined later in, for example, an abstract: Use a separate file (myabstract.Rnw) for the abstract, add \input{myabstract} where the abstract is supposed to be included and knit myabstract.Rnw at the very end of the main document:

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

Key to understanding how this works is to realize that knitr processes the document before LaTeX does. Therefore, it doesn't matter that the LaTeX command \input{myabstract} includes myabstract.tex "before" (not referring to time but referring to the line number), knit("myabstract.Rnw") generates myabstract.tex.


For more complex scenarios, evaluation and output could be separated: Do all the calculations in early chunks and print the results where they belong. To show source code, reuse chunks (setting eval = FALSE). Using the example from above, that means:

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



回答2:


From an intuitive point of view it makes sense that this throws an error: How can you talk about the value of an object that is yet to be computed?

A possible workaround is to run the code chunk before but have include=FALSE and then reuse the code chunk later, see 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}


来源:https://stackoverflow.com/questions/24498362/how-to-force-knitr-to-evaluate-sexpr-after-all-other-code-chunks

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