我正在使用 RStudio 0.98.501 和 MacTex 2013 运行分析并编译手稿。在我的设置中,我使用 master.rnw
定义 LaTeX 模板的文件。该文件输入了一些合作者贡献的手稿 .tex 文件(它们实际上是 work in Word and I convert to .tex ,但这在这里并不重要)。
保持 master.rnw
中的元素清洁,我将分析编码为 child .rnw
file并将我的分析手稿文本写在同一个子文件中。在这个 child 的 R 代码块中定义一个对象很容易 .rnw
文件,例如 result <- 1+2
并在子 .rnw
中引用此对象文本,例如 \Sexpr{result}
.
我遇到了一种情况,我想在运行分析子程序之前引用一个分析对象.rnw
文件—在单独的方法部分报告基本 N=100 .tex
– 所以我尝试了两种从 master.rnw
运行基本分析的方法输入 methods.tex
之前的文件引用对象的文件:(a) 运行一个子文件,该子文件来源为 .R
文件和 (b) 采购 .R
来自 master.rnw
中的代码块的文件文件。我认为结果不应该有差异。就我而言,没有:它们都失败了。
在 .tex
中引用时,LaTeX 无法识别 R 对象。我包括的文件。当然,当我从 master.rnw
中引用 R 对象时,它会很好。文件。有没有办法使用\Sexpr
在 .tex
文件并让 LaTeX 抓取 R 对象?
我创建了一个最小示例并将文件上传到 GitHub如果有人想尝试一下。
% Knitr child example
<<knitr, include=FALSE>>=
library(knitr)
opts_knit$set(self.contained=FALSE)
@
\documentclass{article}
\begin{document}
% run analysis and reference objects, codeA and codeB, via \Sexpr{} in methods.tex that is included later
% attempt 1: run source file defining codeA object via a child rnw file
<<pre-results1, child='child1.rnw', include=FALSE>>=
# child1.rnw runs source("codeA.R")
@
% attempt 2: run source file defining codeB object directly
<<pre-results2>>=
source("codeB.R")
@
% Methods section from tex file
\input{methods}
% in this file we try to grab the two objects codeA and codeB
% Referencing codeA: \Sexpr{codeA}
% Referencing codeB: \Sexpr{codeB}
\section*{Results}
% we know this works: define codeC and reference in the master file
<<results>>=
codeC <- 5
print(codeC)
@
Referencing codeC: \Sexpr{codeC}
\end{document}
最佳答案
knit
不解析 tex 命令,所以 methods.tex
不会在 knit
上读出亭时间。
对于解决方法,试试这个:
<<knitr, include=FALSE>>=
library(knitr)
opts_knit$set(self.contained=FALSE)
file.copy("methods.tex", "methods.rnw")
@
\documentclass{article}
\begin{document}
<<pre-results1, child='child.rnw', include=FALSE>>=
@
<<pre-results2>>=
source("codeB.R")
@
% Methods section from rnw file
<<child="methods.rnw">>=
@
\end{document}
关于r -\Sexpr{} 在 .tex 文件中引用 R 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22975316/