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

邮差的信 提交于 2019-12-18 09:07:09

问题


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}

回答1:


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}



回答2:


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}.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/18581027/using-an-r-variable-before-the-code-chunk-in-which-the-variable-was-created

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!