Reputation: 78
I would like to include an R calculation in the abstract. The R calculation is at the bottom of document, so when I compile the Rnw
file I get an error.
Here is a minimal example:
\documentclass{article}
\begin{document}
\begin{abstract}
This paper... and we got a mean of \Sexpr{mean.data}.
\end{abstract}
<<>>=
data <- c(1,2,3,4,5)
mean.data <- mean(data)
@
\end{document}
Upvotes: 3
Views: 493
Reputation: 30104
You can use the knitr::load_cache()
function as demonstrated in the example 114-load-cache.Rmd
in the repo https://github.com/yihui/knitr-examples. Below is how to use the function in your case:
\documentclass{article}
\begin{document}
\begin{abstract}
This paper... and we got a mean of \Sexpr{knitr::load_cache('test-a', 'mean.data')}.
\end{abstract}
<<test-a, cache=TRUE>>=
data <- c(1,2,3,4,5)
mean.data <- mean(data)
@
\end{document}
The first time when you compile this document, mean.data
won't be available, but it will be read from the cache when you recompile the document.
Upvotes: 3
Reputation: 58825
An alternative approach if you are using LaTeX is to rearrange the order of the output in the LaTeX processing stage. I asked a somewhat similar question on the TeX stack exchange site.
The approach uses the filecontents
(LaTeX) package to store part of the output and then replay it later. In this approach, your abstract would actually be defined at the end of the document, but everything above it would be stored in a file and then reinserted after the abstract during the LaTeX processing step.
Upvotes: 0
Reputation: 32351
If you need the computations to appear after the abstract, you can save the result to a file, and load it in the abstract. You have to compile the LaTeX file twice.
\documentclass{article}
\begin{document}
\begin{abstract}
This paper... and we got a mean of \Sexpr{load("a.RData"); mean.data}.
\end{abstract}
<<Computations>>=
data <- c(1,2,3,4,5)
mean.data <- mean(data)
save(mean.data, file="a.RData")
@
\end{document}
Upvotes: 2
Reputation: 368181
Well you obviously need to move the definition of something being used before it is being used, not after. So try this instead:
\documentclass{article}
\begin{document}
<<>>=
data <- c(1,2,3,4,5)
mean.data <- mean(data)
@
\begin{abstract}
This paper... and we got a mean of \Sexpr{mean.data}.
\end{abstract}
\end{document}
Chunks can occur just about everywhere, including before \begin{document}
.
Upvotes: 4