Skip to content

, ,

PDFs of R output – Sweave

April 11, 2013

One of the great things about R is that if you use scripts, you have a record of what you’ve done. If you copy the console output into the script then you also have a copy of that. Brilliant…until you forget or get lazy.

But what if you could make a pdf of your work? Using Sweave (S being then language that R is based on and weave being the verb), you can. But it does use LaTeX, so you have to learn a little bit of that too, as well as install it. Check out CTAN – the LaTeX equivalent of CRAN

If you use RStudio, this is really easy though. You open a new “R Sweave” file which already has most of what you need to begin – the bones of the LaTeX document:




After the \SweaveOpts line you can start typing any description of the analysis youre doing. To start an “R chunk” (some code for R to interpret) you type


enter your R code and then type


to end it. So a short file might look like this:

\usepackage[top=1in, bottom=1in, left=1in, right=1in]{geometry}

Open the cars dataset:


Show a summary of the dataset:


Make a figure

plot(cars[,1], cars[,2])


I added a couple of lines to the code to make it look a little different – the line with top, bottom etc just alters the margins using the geometry package. I also added \usepackage[noae]{Sweave} because ‘ symbols stop it working…the [noae] allows it to include them.For the figure I included the fig=TRUE between the << and >> to tell LaTeX to include the figure. There are other arguments to tell it to ignore the section or just return the result etc.

Once youve got that, you just hit the “Compile PDF” button on the RStudio tool bar.

If you dont use RStudio, you have to use the Sweave function

help("Sweave", package="utils")

I hope someone finds this helpful!!

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: