[Tex/LaTex] execute R code in latex file imported from separate R file

knitrmarkdownr

My personal objective in this Rnotebook revolution where typesetting and number crunching cohabitate is to keep R files separate from latex and as little polluted by markdown as possible and only in the form of R comments, like with javadoc for example or even perlpod. And in that I have succeeded so far by producing readable R-reports with minimal markdown safely confined within comment fences. Then from an R cli session one can do: library(rmarkdown); render('afile.R').

Now I am trying to typeset with latex and crunch with R.

But again: try to keep R and latex files separate. So instead of following what many naive examples on the net do (and end up in hell when files grow):

\documentclass[12pt]{article}
\begin{document}

Hello I am latex
<<echo=F>>=
cat('and I am R and 1+1 is ', 1+1)

x1 <- runif(1000,1,2)
hist(x1,breaks=10)
@
\end{document}

Ideally, I would like to do this:

\documentclass[12pt]{article}
\begin{document}

Hello I am latex and following is my R script:

\input{crunch.R}

\end{document}

where crunch.R is:

cat('and I am R and 1+1 is ', 1+1)

x1 <- runif(1000,1,2)
hist(x1,breaks=10)

Unfortunately this does not work because the input is not enclosed in <<>>= and @.

But neither does this crunch.R work (additionally the file can not be processed by R correctly):

<<>>=
cat('and I am R and 1+1 is ', 1+1)

x1 <- runif(1000,1,2)
hist(x1,breaks=10)
@

Nor this latex file:

\documentclass[12pt]{article}
\begin{document}

Hello I am latex and following is my R script:

<<>>=
\input{crunch.R}
@

\end{document}

for obvious reasons.

What I need is a special \inputR{filename.R} latex command which will take care of inserting the tags <<>>= and @.

Any idea where to find this command or how to write it?

Best Answer

You can load external chunks using read_chunk and then execute them later. This simplifies the source document and allows you to keep code external. See Code Externalization.

So assume your R code is called Rcode.R This has an R comment line with the label of the code to be used in your .Rnw file, in this example the label is external-code. It looks like this:

# ---- external-code ----
cat('and I am R and 1+1 is ', 1+1)

x1 <- runif(1000,1,2)
hist(x1,breaks=10)

Now we have the following .Rnw file. Notice that this first reads the code, and then executes it separately. The code is referred to using the label defined in the Rcode.R file.

\documentclass[12pt]{article}
\begin{document}

Hello I am latex

<<external-code, cache=FALSE,echo=F>>=
read_chunk('Rcode.R')
@

<<external-code,echo=F>>=
@

\end{document}

You get the following output:

output of code