Sweave (Latex interface with R)

I have found Sweave is great for at least two things: generating automated reports and writing R tutorials with code. 

First, R needs a working directory (file folder on your computer) set to where you want to make the Latex output. The working directory  can be set using setwd() in R. You can see what working directory is currently assigned with getwd().  Sometimes I load a saved .RData environment with data using load().  I almost always add library(xtable) to automatically generate tables in Latex.  You also need to add the Sweave.sty file to the working directory, which can be found online.

Second, Latex needs to be set up.  Make a new Latex file, see the attachment below for an example .Rnw.  All changes should be made to the .Rnw file and not the .tex file.  Save the .Rnw file.

Third, in R run the sweave command. Assuming the .Rnw is in the working directory the command is: Sweave(paste(getwd(),"/example.Rnw",sep="")).  R will generate a .tex file from the .Rnw file in the working directory and create any plots (I have it set to make .eps plots). 

Finally, open the newly created .tex file and compile it.  If there are errors, do not fix them in the .tex, go back to the .Rnw and fix them. Then re-run the Sweave command in R and re-open the new .tex file and try compiling it again.  It can take a bit of back and forth work between R and Latex to get everything set but it will eventually produce a nice automated report. I usually have three applications open: R, .Rnw latex window, and .tex latex window. 

example.Rnw

example.tex

example.pdf