【问题标题】:Using an R variable before the code chunk in which the variable was created在创建变量的代码块之前使用 R 变量
【发布时间】:2013-09-02 21:31:55
【问题描述】:

我想在摘要中包含一个 R 计算。 R 计算在文档的底部,所以当我编译 Rnw 文件时出现错误。

这是一个最小的例子:

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

【问题讨论】:

  • 目前,knitr 以线性方式执行代码块和内联表达式,因此您不能使用“未来”对象;但如果缓存数据库存在,我可能会在未来提供一些东西让您从未来的缓存中加载对象
  • 我在下面提供了一个例子:stackoverflow.com/a/58104427/559676

标签: r knitr


【解决方案1】:

嗯,你显然需要在使用之前移动它的定义,而不是之后。所以试试这个:

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

块几乎无处不在,包括之前 \begin{document}

【讨论】:

  • 是的,但是对于摘要/摘要之类的内容,能够从“未来”块加载数据是很有用的功能。 Yihui 的回复有一个缓存结果的方法,这在这种情况下很有用。
  • @Vincent's 大约六年前出现也是如此,而且这些都不能证伪我的说法,即您需要在使用之前计算一些东西。只需三种不同的方法即可。 .
【解决方案2】:

您可以使用knitr::load_cache() 函数,如repo https://github.com/yihui/knitr-examples 中的示例114-load-cache.Rmd 中所示。以下是在您的情况下如何使用该功能:

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

第一次编译该文档时,mean.data不可用,但重新编译该文档时会从缓存中读取。

【讨论】:

    【解决方案3】:

    如果您需要计算出现在摘要之后, 您可以将结果保存到文件中,并将其加载到摘要中。 你必须编译 LaTeX 文件两次。

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

    【讨论】:

      【解决方案4】:

      如果您使用 LaTeX,另一种方法是在 LaTeX 处理阶段重新排列输出的顺序。我问了somewhat similar question on the TeX stack exchange site

      该方法使用filecontents (LaTeX) 包来存储部分输出,然后稍后重放。在这种方法中,您的摘要实际上会在文档末尾定义,但上面的所有内容都将存储在一个文件中,然后在 LaTeX 处理步骤期间重新插入摘要之后。

      【讨论】:

        猜你喜欢
        • 2022-01-05
        • 2011-12-12
        • 2022-01-10
        • 1970-01-01
        • 1970-01-01
        • 2021-04-20
        • 1970-01-01
        • 2018-10-31
        • 2012-06-09
        相关资源
        最近更新 更多