# Rstudio, Sweave, and LaTeX

(pronounced Lay-tech, the X is supposed to be a capital ) is a typesetting environment used to generate a professional looking output, and automate some of the more tedious tasks of writing a paper. It is the de-facto standard for writing scientific papers, and it is a good idea to learn it if you intend to release academically. Also, if you’ve been frustrated fiddling with Microsoft’s Equation Editor for writing your papers, LaTeX will alleviate your pain.

Rstudio is an integrated development environment for the R statistical programming language. It makes most programming tasks with R much easier and more productive. Packaged in Rstudio are plugins that allow for the merging of R output (code, data, graphs) and the typesetting abilities of . To take advantage of this, you will additionally need a Installation. The one I will recommend here is MiKTeX.

These recommendations are of course based on the user using Microsoft Windows. If that is not the case, then for using Linux the recommendation changes to TeXLive or teTeX. The Mac recommendation is MacTeX. There are some differences between the distributions in what they will support. A document that compiles without issue on one may not compile on another.

Sweave
Sweave is the transition piece between R and LaTeX. Named for S-Weave (S being the closed-source statistical language R is emulating), Sweave “weaves” R code and output into LaTeX documents. Within Rstudio, you create a Sweave document (with the .Rnw extension) and encapsulate R code into “chunks”. Within those chunks, any R code can be run, and output presented as R natively would. Below is a sample .Rnw file to demonstrate this.

\documentclass{article}
# options for the document go here.
# load LateX packages, declare new macros
\begin{document}

<<>>=
# this is an R code chunk.  R code goes in here,
# between the angle brackets and the at symbol.
a = 123456
print(a)
@
This will declare the variable a and print it as R would,
within the R chunk.  If we want to output the results of R
inline into document text, then we can do so with Sexpr.
The content of the variable a is \Sexpr{a}.
\end{document}


Within the code chunk declaration, we can set various options for the chunk. If we intend to have the chunk make a plot, we would need to declare fig=TRUE within the chunk declaration. If we intend to hide the code used, but still let it run, then we set echo=FALSE. If we don’t intend the code to run, merely display it, then we would use eval=FALSE. There are many other options available for our use.