A very simple Sweave Demo
Karsten D. Wolf
January 6, 2009
1 Introduction
As you can read on my World of R-Craft blog (worldofrcraft.blogspot.com/),
it is rather easy to setup your Mac to be a reproducible research workstation.
Just mix and match the power of R and LATEX. Right now I am still a bit rusty
on my LATEXside of things, but I will definitely improve on that over the course
of the next months.
2 First examples
Now, let’s do a quick example
> 2 * 1024
[1] 2048
What I actually typed in firstDemo.Rnw was
<<exampleOne>>=
2 * 1024
@
As you can see (or at least, suspect): this is not LATEX. It is a so called “code
chunk” to be processed by Sweave. Sweave processes all the R code chunks and
stuffs the output in the LATEX file it is creating. That is all very well, but you
can also do some R processing, hide the most of it and then - bang! - show some
of it. That is very convenient if you are doing longer analysis and just want to
show that table with all of the results. Now let’s do this! Right here! I have just
created a vector V01 with all the integers from 1 to 100! But now you didn’t
see it. I typed
<<exampleTwo, echo=FALSE, include=FALSE>>=
v01 <- c(1:100)
@
1
The echo=FALSE, include=FALSE does the trick. Echo=FALSE means no display
of my input. Include=FALSE means no display of output. Nada! Later I can
use the results of my code, because all of the R code in my document is run in
one session:
> length(v01)
[1] 100
3 Examples with graphics
Text is all and well, but we want to see graphics in our documents. Let’s create
some data we can plot:
> par(bg = "white")
> n <- 100
> set.seed(43214)
> x <- c(0, cumsum(rnorm(n)))
> y <- c(0, cumsum(rnorm(n)))
> xx <- c(0:n, n:0)
> yy <- c(x, rev(y))
Figure 1 (p. 3) is produced by the following code
> plot(xx, yy, type = "n", xlab = "Time", ylab = "Distance")
> polygon(xx, yy, col = "gray")
> title("Distance Between Brownian Motions")
You need to have a look at the sourcecode of firstDemo.Rnw to see how I
did this. I will explain this and give more examples over the next weeks. For
now I am really happy with the results of my experiments today.
See you soon!
2
Distance Between Brownian Motions
5
Distance
0
−5
0 20 40 60 80 100
Time
Figure 1: Distance between brownian motions