r -\Sexpr{} 在 .tex 文件中引用 R 对象

标签 r latex knitr rstudio

我正在使用 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/

相关文章:

r - quantstrat:如何在同一柱上执行?

r - 是否可以在 R 中求解代数方程?

r - 在 Ubuntu 14.04LTS 上安装 Pandoc 以与 R Markdown 一起使用时出现问题

r - 使用 knit 和 Rstudio 自动调整 LaTeX 表格宽度以适合 pdf

r - 用 table() 计数并排除 0

r - 如何删除在 Quarto v1.3 的 callout-block 中打印 huxtable 时添加的水平线?

latex - Tikz:节点组的水平居中

r - 如何在动态文档 R 和knitr 中创建自定义章节标题

latex - 在Knitr中,如何使用Latex中的\textwidth设置图形宽度

R Shiny : code output inside markdown table cell