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
@
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.
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).
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.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With