Carlos
Carlos

Reputation: 78

Using an R variable before the code chunk in which the variable was created

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

Answers (4)

Yihui Xie
Yihui Xie

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

Brian Diggs
Brian Diggs

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

Vincent Zoonekynd
Vincent Zoonekynd

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

Dirk is no longer here
Dirk is no longer here

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

Related Questions