Freitag, 28. November 2008

First and easy steps with R and Sweave

What really sold me to the idea of using Sweave and therefore (re)learning LaTeX was the idea of Reproducible Research. Charlie Geyer has put together some examples how to mix and match R and LaTeX with Sweave. Today's goal therefore is to run his examples and to see, what problems I run into :)

Allright, if you all go to the example section of Charlie's Reproducible Research Page, you will find three examples. Let's start with the first one.

To start, I created a folder ReproducibleResearch, copied my Sweave.sty file into it and created a project within Textmate by dragging the folder onto the Textmate icon in my dock. Then I created a document foo.Rnw, copied the contents of the first example into it and saved it (if you have the R, SWeave and LaTeX bundles installed, TextMate should be recognizing this *.Rnw document as a Sweave document.

Feeling lucky, I just pressed cmd-R to run this code in R.


It just worked. Wow! A TextMate "Sweave, Typeset & View" window just showed me "An (sic!) Sweave Demo" by Charles J. Geyer! Complete with LaTeX typesetting, R output and even graphics. That's what I want, so this is a great start! Many kudos to Charles.

Now, let's analyse the code to see what we can rip off this example.




\title{An Sweave Demo}
\author{Charles J. Geyer}

All right, so this is just plain LaTeX. It is a document of class article, it uses some packages, it begins the document and defines a title. Doesn't look pretty in code, but hey, this is LaTeX - you better get used to this ;)

This is a demo for using the \verb@Sweave@ command in R. To
get started make a regular \LaTeX\ file (like this one) but
give it the suffix \verb@.Rnw@ instead of \verb@.tex@ and then
turn it into a \LaTeX\ file (\verb@foo.tex@) with the (unix) command
R CMD Sweave foo.Rnw
So you can do
latex foo
xdvi foo
and so forth.

Now there is some text - all this \verb@sometext@ gives you a code-like text formating within normal text. \begin{verbatim} starts a code block, \end{verbatim} stops it. Pretty standard LaTeX stuff.

A few lines later it gets more interesting:

2 + 2

Alright, so this is a code chunk, which will be run and the output of R will be written. Very nice! Try it out and alter the 2 + 2 to something else and sweave the file again. I typed in 2 * 1024 - 35 and the result has been 2013. Easy enough.

In the next post I will digg deeper into creating graphs and doing more complex analysis reports with Sweave. For tonight, I am happy with the first results.

Keine Kommentare: