简体   繁体   中英

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

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
@

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}

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM