= set_parent("parent.Rnw") x @ 我可以运行父文档。但是,-6ren">
gpt4 book ai didi

r - 使用 knitr 时,我可以在子 Rnw 文档之间交换数据吗?

转载 作者:行者123 更新时间:2023-12-01 12:30:28 28 4
gpt4 key购买 nike

父文档如下:

<<child = "child1.Rnw">>=
@
<<child = "child2.Rnw">>=
@

child 1:

<<>>=
set_parent("parent.Rnw")
x <- 1
@

child 2:

<<>>=
set_parent("parent.Rnw")
x
@

我可以运行父文档。但是,我无法单独运行 child 2 文档。似乎子文件 2 看不到子文件 1 中定义的变量 x。如何单独运行 child 2 文档?

最佳答案

set_parent 未按您预期的方式工作。来自 ?set_parent:

This function extracts the LaTeX preamble of the parent document to use for the child document, so that the child document can be compiled as an individual document.

set_parent("parent.Rnw") 不会编织整个父文档,它只会提取序言。因此,有了这个 parent.Rnw 文件

\documentclass{article}
\begin{document}

<<child = "child1.Rnw">>=
@

<<child = "child2.Rnw">>=
@

\end{document}

child2.Rnw 不能单独编译,因为 child1.Rnw 在那种情况下不运行。

有效的是以下1:

knit("parent.Rnw")
knit("child2.Rnw")

由于两个文档都是在相同的环境中计算的(参见 knit 的默认 envir 值),来自 parent.Rnw 的对象(和it's child) 可用于后续编织child2.Rnw

此外,?set_parent 提供了另一种选择:

When the preamble of the parent document also contains code chunks and inline R code, they will be evaluated as if they were in this child document.

如果可以重新排列 parent.Rnw 使得引用 child1.Rnw 的 block 在序言中

\documentclass{article}

<<child = "child1.Rnw">>=
@

\begin{document}

<<child = "child2.Rnw">>=
@

\end{document}

然后 child2.Rnw 可以被编织而无需事先编织 parent.Rnw


1 出于某种原因, knit2pdf("child2.Rnw") 崩溃 pdflatex.exe(通过调用 texify.exe) 在我的系统上。然而,PDF 文件是正确生成的,并且直接在 TEX 文件上运行 pdflatex 不会造成任何问题。 Nevermind .

关于r - 使用 knitr 时,我可以在子 Rnw 文档之间交换数据吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34574704/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com