I am using RStudio 0.98.501 and MacTex 2013 to run an analysis and compile a manuscript. In my setup, I use a master.rnw
file that defines the LaTeX template. This file inputs a few manuscript .tex files that collaborators contribute to (they actually work in Word and I convert to .tex, but that is not important here).
To keep things clean in the master.rnw
, I code the analysis in a child .rnw
file and write my analysis manuscript text in the same child file. It's easy to define an object in an R code chunk in this child .rnw
file, e.g., result <- 1+2
and reference this object in the child .rnw
text, e.g., \Sexpr{result}
.
I encountered a situation where I wanted to reference an analysis object before running the analysis child .rnw
file—reporting a basic N=100 in the separate methods section .tex
–so I tried two ways of running my basic analysis from the master.rnw
file before inputting the methods.tex
file that references the objects: (a) running a child file that sources a .R
file and (b) sourcing the .R
file from a code chunk in the master.rnw
file. I don't think there should be a difference in outcomes. In my case there is not: they both fail.
LaTeX does not recognize the R objects when referenced in a .tex
file I include. Of course it does fine when I reference an R object from within the master.rnw
file. Is there a way to use \Sexpr
in a .tex
file and have LaTeX grab the R object?
I created a minimal example and uploaded the files to GitHub if anyone wants to take a crack at it.
% 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}