Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

latex

knitr

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
@
like image 243
Sam Avatar asked Jun 30 '14 20:06

Sam


People also ask

How do you not run a chunk in R markdown?

If you don't want any code chunks to run you can add eval = FALSE in your setup chunk with knitr::opts_chunk$set() . If you want only some chunks to run you can add eval = FALSE to only the chunk headers of those you don't want to run.

How do you enter a chunk code in R?

You can insert an R code chunk either using the RStudio toolbar (the Insert button) or the keyboard shortcut Ctrl + Alt + I ( Cmd + Option + I on macOS).

What is a code chunk?

A code chunk is a runable piece of R code. Re-producing the document will re-run calculations. Code chunk technology is beneficial because the risk of mismatch between the commentary in a paper and the results being discussed is reduced.


1 Answers

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}
like image 129
CL. Avatar answered Oct 25 '22 14:10

CL.