【问题标题】:\Sexpr{} in a .tex file to reference R object\Sexpr{} 在 .tex 文件中引用 R 对象
【发布时间】:2014-04-09 22:40:36
【问题描述】:

我正在使用 RStudio 0.98.501 和 MacTex 2013 运行分析并编译手稿。在我的设置中,我使用了一个定义 LaTeX 模板的master.rnw 文件。这个文件输入了一些合作者贡献的手稿 .tex 文件(它们实际上是work in Word and I convert to .tex,但这在这里并不重要)。

为了在master.rnw 中保持干净,我在child .rnw file 中编写分析代码,并将我的分析手稿文本写入同一个子文件中。在这个子 .rnw 文件中的 R 代码块中定义一个对象很容易,例如,result <- 1+2,并在子 .rnw 文本中引用这个对象,例如,\Sexpr{result}

我遇到了一种情况,我想在运行分析子 .rnw 文件之前引用一个分析对象——在单独的方法部分报告基本 N=100 .tex——所以我尝试了两种运行基本分析的方法在输入引用对象的methods.tex 文件之前,从master.rnw 文件中获取:(a) 运行一个子文件,该子文件获取.R 文件和(b) 从@987654337 中的代码块获取.R 文件@ 文件。我认为结果不应该有差异。就我而言,没有:它们都失败了。

在我包含的.tex 文件中引用时,LaTeX 无法识别 R 对象。当然,当我从master.rnw 文件中引用一个 R 对象时,它确实很好。有没有办法在.tex 文件中使用\Sexpr 并让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}

【问题讨论】:

  • 我还没有测试过,但是将methods.tex 重命名为methods.rnw 并通过child 包含它不起作用吗?

标签: r latex knitr rstudio


【解决方案1】:

knit 不解析 tex 命令,所以methods.tex 不会在knitting-time 被读出。

对于解决方法,试试这个:

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

【讨论】:

  • 很好的解决方案。如此简单。
猜你喜欢
  • 1970-01-01
  • 2012-01-16
  • 1970-01-01
  • 1970-01-01
  • 2016-05-13
  • 2021-05-28
  • 2012-05-24
  • 2021-12-19
  • 1970-01-01
相关资源
最近更新 更多