Using knit spin or stitch to interleave R into a template - r

This is probably documented somewhere, but I cannot find it ...
I have an .R file which can be used as a read_chunk() file and call from an .Rnw latex template or in a .Rmd file for primary review.
This design worked well for the first part of our project, but since the .R file will change, it's not 'reproducible research'.
Since I already have a 'template' with the named chunks referring to chunks in the read_chunk() file, is there any way to interleave the R into the .Rnw for posterity?

You want the reverse operation of purl(), I believe. I don't know any such function, but technically it doesn't seem too hard; all the pieces are there:
chunks <- knitr:::knit_code$get()
for(k in names(chunks))
cat(c(sprintf("<<%s>>=", k), chunks[[k]], "#\n"), sep = "\n")
would return all the chunks in a format suitable for inclusion in the Rnw file.

Related

Long documents on R Sweave include files

I'm writing a book in R Sweave, as long as the document is becoming larger I use the \include LaTeX command to include files. When I PDF-Compile the main file the files with R chunks are not included. What extension they must have .tex or .Rnw?
From the Sweave User Manual, p. 7
Latex files can include others via \input{} commands. These can
also be used in Sweave files, but the included files will be included by
Latex and are not processed by Sweave. The equivalent if you want
the included files to be processed is the \SweaveInput{} command.
Included files should use the same Sweave syntax (see below) and
encoding as the main file.

How to remove .tex after running knit and texi2pdf

I have an R data frame that I run through knitr using the following code:
knit('reportTemplate.Rnw', 'file.tex') # creates a .tex file from the .Rnw one
texi2pdf('file.tex') # creates a .pdf file from the .tex one
Inside my R script, I want to remove 'file.tex' from my computer folder afterwards. How do I achieve this? It is important that I do this within my .R file, since those lines are actually inside a loop that generates 1000 different reports from that template.
There are a family of functions in R that allow the user to interact with the computer's file system. Run ?files to see functions that make it possible to, for instance, create, rename and remove files.
As noted by Josh O'Brien, in a comment to the OP, in this specific case, the command to be used is file.remove('file.tex').

Send parameters to child Knitr file

I have some identical sections in a document but the entry data's files are differents.
Is it possible to make a master knitr file who all sections are wrote and call a child Knitr-file, who have the code for the corps of all section (identical code), but take as parameter the datafiles ?
Lile if we passed some parameters to a R-script sourced in another script.
One solution is this workflow:
Write the knitr file (Rnw or rmd, whatever) which uses a few variables that are not defined in that script.
Write a function that knits the knitr file, and takes a bunch of arguments that the knitr file should use (these should correspond in name to the variables I refer to in 1.)
Then knit using the envir argument (assuming it is an rmd file):
knitrenv <- new.env()
assign("someargument", someargument, knitrenv)
assign("someargument2", someargument2, knitrenv)
knit2html(myrmdfile, envir=knitrenv)

How to extract all code chunks from a Rnw Sweave file?

I received a .Rnw file that gives errors when trying to build the package it belongs to. Problem is, when checking the package using the tools in RStudio, I get no useful error information whatsoever. So I need to figure out first on what code line the error occurs.
In order to figure this out, I wrote this 5-minute hack to get all code chunks in a separate file. I have the feeling though I'm missing something. What is the clean way of extracting all code in an Rnw file just like you run a script file? Is there a function to either extract all, or run all in such a way you can find out at which line the error occurs?
My hack:
ExtractChunks <- function(file.in,file.out,...){
isRnw <- grepl(".Rnw$",file.in)
if(!isRnw) stop("file.in should be an Rnw file")
thelines <- readLines(file.in)
startid <- grep("^[^%].+>>=$",thelines)
nocode <- grep("^<<",thelines[startid+1]) # when using labels.
codestart <- startid[-nocode]
out <- sapply(codestart,function(i){
tmp <- thelines[-seq_len(i)]
endid <- grep("^#",tmp)[1] # take into account trailing spaces / comments
c("# Chunk",tmp[seq_len(endid-1)])
})
writeLines(unlist(out),file.out)
}
The two strategies are Stangle (for a Sweave variant) and purl for a knitr variant. My impression for .Rnw files is that they are more or less equivalent, but purl should work for other types of files, as well.
Some simple examples:
f <- 'somefile.Rnw'
knitr::purl(f)
Stangle(f)
Either way you can then run the created code file using source.
Note: This post describes an chunk option for knitr to selectively purl chunks, which may be helpful, too.

How do I Sweave a multiple-file project?

I am writing my thesis in LaTeX and because things got a bit long for my taste, I had split it into several files. Let's call them thesis.tex, intro.tex, mat_n_met.tex, rslts.tex and discsn.tex. I have linked intro.tex, mat_n_met.tex, rslts.tex and discsn.tex through thesis.tex with \include{intro} (and so on...).
I have also created a separate file called r_crunching.Rnw (that I run through Sweave) that holds a chunk that runs the R script with data analysis and chunks that produce pdf outputs of graphs that I embed via \includegraphics (in e.g., rslts.tex). Still following?
If I run a Rnw (i.e. I renamed rslts.tex to rslts.Rnw) without "a link" to the chunk with the R script, you will get a Sweave() error saying the reference in \Sexpr{} doesn't exist. Is there a way, without merging all the files into a single .Rnw, to call \Sexpr{} in say rslts.Rnw?
Other methods how to accomplish this are welcome.
I recommend using RStudio (http://www.rstudio.com/ide/). Sweave is nicely integrated into that IDE and it supports multi-file documents. Even Synctex and TeX error log navigation still work when working with multi-file documents.
From the master file you can include child files using
\SweaveInput{Child.Rnw}
You can link a child file back to the master file by including the directive
% !Rnw root = Master.Rnw
in the child file. That way when working on a child file and typesetting it, RStudio know to typeset the master file.
The details are explained in the RStudio documentation at http://www.rstudio.com/ide/docs/authoring/multiple_rnw_files
Forget for a second that you are dealing with Sweave and just think of the latex problem -- for which \include and \includeonly offer solutions. Try that with a few simple test files.
Once you have that figured out, fold Sweave back into the mix and it just work as Sweave is after 'merely' a pre-processing step, albeit a very clever one.
To expand Dirk's and mjm's answer, I would suggest using \include's and Makefiles.
Suppose you have a master file: master.tex. In that file, you include some .tex and .Rnw files, i.e.
\include chapter1
\include chapter2
\include chapter3
....
Now the following Makefile provides functions for creating the .tex, .R and .pdf files:
.SUFFIXES: .tex .pdf .Rnw .R
MAIN = master
##List your your .Rnw includes
RNWINCLUDES = chapter1 chapter2 chapter3
TEX = $(RNWINCLUDES:=.tex)
RFILES = $(RNWINCLUDES:=.R)
RNWFILES = $(INCLUDES:=.Rnw)
all: $(MAIN).pdf
$(MAIN).pdf: $(TEX) $(MAIN).tex
R: $(RFILES)
.Rnw.R:
R CMD Stangle $<
.Rnw.tex:
R CMD Sweave $<
.tex.pdf:
pdflatex $<
bibtex $*
pdflatex $<
pdflatex $<
Essentially, the .SUFFIXES provide a set of rules for convert from one file format to another. For example, to convert from .Rnw to .R, we use the command
`R CMD Stangle $<`
one fairly obvious answer is to use a makefile, possibly using package cachesweave, to process the relevant files in the right order.
My solution to multi-file projects in Sweave (under Rstudio) is the following:
1) Create a master file, say master.Rnw, in which you have the calls to the subfiles intro.Rnw, matmet.Rnw, etc:
\documentclass[11pt]{book}
% \usepackage{blah, blah} as you wish
\graphicspath{ {./figs/}
\begin{document}
\SweaveOpts{concordance=TRUE}
\include{intro} % a call to 'intro.Rnw'
\include{matmet} % a call to 'matmet.Rnw'
\include{results} % a call to 'results.Rnw'
\include{discuss} % a call to 'discuss.Rnw'
\end{document}
2) Create the subfiles. I'm giving here only the first one, intro.Rnw. Please note that in the subfiles you do not use preambular commands such as \documentclass or \begin{document}
\chapter{Introduction}\label{ch:intro}
\section{This is section 01}
In section 01 we are concerned about whether \texttt{Sexpr} could possibly work. The chunk below creates a variable \em{a} which will be referred to by this command later on.
<<>>=
a <- 1+2
#
Ok, if it is working, we shall see number 3 right here: \Sexpr{a}.
3) After saving modifications in 'intro.Rnw', simply go to 'master.Rnw' and compile it using Ctrl+Shift+K and... voilá:
Screenshot of the file created by the above command.

Resources