Get ready to Sweave!

This tutorial provides a brief overview of how to create Sweave (LaTeX + R) documents in APA style.

0: Setup

Install LaTeX packages

In order to create LaTeX documents, you need to install LaTeX libraries on your computer. Here are links to Mac and Windows LaTeX libraries

Install R and RStudio

Install the latest versions of R and RStudio

Install R packages

Next you should install some R packages that will help you create Sweave documents. Open RStudio and run the following two lines of code:

# These packages help with Sweave
install.packages("knitr")
install.packages("xtable")

Update RStudio preferences

Next, you’ll need to change some of the the RStudio Sweave preferences.

Go to RStudio – Preferences – Sweave and make the following two changes:

  • Select “Sweave Rnw files using Knitr
  • Set “Preview PDF” with “System Viewer”

1: A simple APA Sweave Template

Ok you’re ready to create your first Sweave file!

  1. Open a new Sweave file in RSTudio: File – New File – R Sweave.

When you do this, you’ll see a bare-bones file with a three commands.

  1. Save the file under a new name with the .Rnw suffix (e.g.; myfirstsweave.Rnw)
  2. Now open a web-browser and go to the following address to find an APA style Sweave template (Simple APA Sweave File)
  3. Copy and paste all of the text from the template and paste it into your Sweave file.
  4. Click the “Compile PDF” button at the top of your screen. When you do this, you should see some processing output, followed by a PDF!

2: Basic LaTeX commands

Important aspects of the document, such as the title, author, and affiliation are specified with commands in the form \command{}.

  • The main aspects of your document such as the title, header, and author are specified with commands like \title{}, \shorttitle{}, \author{}.

  • Sections are defined using the \section{} and \subsection{} commands. For example, to start the Method section, you write \section{Method}. To include the Participants subsection, you write \subsection{Participants}

  • Bold and italic text are created with the \bf{} and \emph{} commands:

    • SWEAVE: Here is how you write \bf{bold text}, here is how you write \emph{italic text}.
    • PDF: Here is how you write bold text, here is how you write italic text.

3: R code chunks

You can incorporate R code into your Sweave document in one of two ways: with regular chunks, or with mini-chunks. Everything you put in an R chunk will be evaluated as R code.

Regular R chunks

Regular R chunks start with a start ‘tag’ <<>>= and end with an end ‘tag’ @. They are indicated with gray backgrounds and look like this:

You can create a new R chunk either by manually typing the start <<>>= and end @ tags, or by clicking the green “Insert a new code chunk” button on the top right of your editor window in RStudio.

You can specify many arguments at the top of the chunk (in between <<>>=) that will change how the code is evaluated. Here are some key arguments:

  • eval: Should to code in the chunk be evaluated (eval = T) or completely ignored (eval = F)? If you have code in a chunk that is not complete, but you still want to create the document without that chunk, set eval = F.

  • echo: Should the raw code be repeated in the final document (echo = T) or not? (echo = F). In most APA style papers you’ll never repeat the code so you’ll usually set echo = F.

  • fig.width, fig.height, fig.align: If your chunk creates a figure, these arguments will change its size and location. For example, fig.width = 4, fig.height = 10, fig.align = ‘center’ will create a centered figure that is 4 inches wide and 10 inches tall.

Setting global chunk options

If you want to change some options for all of your R chunks, you can do this using the ops_chunk$set() function in an R chunk at the beginning of your document. For example, in virtually all of your R chunks you will not want to echo (aka repeat) the source code in the document. For this reason, it’s good to set the global chunk option to echo = F.

Mini-code chunks

If you want to include the output of R code (e.g.; the p-value of a t.test) directly into your text, you should use a mini-chunk. Mini-chunks are specified with the \Sexpr{} command. Everything in the curly braces will be interpreted as R code.

For example, the following sentence in Sweave will be printed in the PDF as follows

  • SWEAVE: The mean age of participants was \Sexpr{mean(data$age)} and there were \Sexpr{sum(data$sex == “f”)} females.
  • PDF: The mean age of participants was 21 and there were 100 females.

4: Including figures

To include figures, use the \begin{figure} and \end{figure} commands. In between these commands, you’ll specify how to create, or find, the figure.

Creating figures in R Chunks

To create the figure directly using R code, create an R chunk that creates the figure. For example, the following code chunk creates a histogram

Importing figures from external files

If your figure is in an external file (like a pdf or jpg), you don’t need to use an R chunk. Instead, you include the figure using the \includegraphics{} command. Just put the name (and possibily the file path) of the figure in the braces.

Additional figure tips

  • If your file is located in a separate folder from your .Rnw file, you’ll also need to include a file path (e.g.; figures/myplot.pdf or /Users/nphillips/Dropbox/Public/myplot.pdf)
  • For more tips on organising figures in LaTeX, check out this link: Customising figures in LaTeX
  • You can change the size and alignment of the figure by adding (or changing) options of the R chunk (e.g.; fig.width = 12, fig.height = 3, fig.align = ‘left’.
  • You can specify the caption under the figure with the \caption{} command.
  • The \label{} command is used for creating an internal label for the figure in Sweave. You can use this label to refer to the figure in your text. For example, as the label of my figure above is fig:s2donation, I can refer to this figure in my text as follows:

    • SWEAVE: A barplot of the donation rates by condition are presented in Figure \ref{fig:s2donation}
    • PDF: A barplot of the donation rates by condition are presented in Figure 2

5: Citing articles and references

References with BibTeX

In LaTeX, you need to specify all of the articles you cite using BibTeX. BibTeX is just a standardized format for documenting references. LaTeX will automatically adjust the formating of your citations and references according to the style of your document (e.g.; APA).

You can easily get new bibtex citations for articles from Google scholar. Just search for an article, click cite – BibTeX. Then copy and paste the BibTeX data into your BibTeX file!

You can include BibTeX references in one of two ways. You can include it directly into your Sweave (.Rnw) file using the \begin{filecontents} command. Just start with the \begin{filecontents}{bibliography.bib} command, then paste all your BibTeX references, then close the command with \end{filecontents}

At the end of the template, you’ll see where I’ve included the BibTeX references.

Finally, you need to include the \bibliography{} argument at the end of your document and tell Sweave the name of your bibliography file (in my case, bibliography.bib).

You can also include your BibTeX references in a separate file. To do this, just save a text file with all of your BibTeX references with the .bib suffix. Then, include the external file name in the \bibliography{} command.

Citing articles in your document

Once you have the BibTeX data for an article, you can cite it in your document using a variation of the \cite{} command. For example, \cite{} will cite an argicle without parentheses, while and \citep{} will include the citation in parentheses. To specify an article, you use the label indicated in the first line of its BibTeX data (beginning with @).

SWEAVE \cite{bargh1996automaticity} published a provocative paper that tested…

PDF Barge, Chen and Burrows (1996) published a provocative paper that tested…

6: Using R packages and reading external data

If you use functions from an external package / library, you must either load the library explicitly in your document in a code chunk using the library() function, or always indicate which package you are using for each function with the package::function() notation (e.g.; BayesFactor::ttestbf()). If you don’t tell Sweave which packages you are using, the functions won’t work and the document will not compile!

Additionally, you must always explicitly define all data objects at the beginning of your document in an R chunk (e.g.; using the read.table() or load() functions). If you don’t, Sweave won’t find them and your R code won’t work!

7: Reading R code from external files

If you have a lot of R code that you want to include in a document, it may not look so nice to include it directly in an R chunk in your Sweave file. For example, you may have a really complicated plot that takes 100 lines of code to create. Rather than putting all that code in a chunk, you can save the code as an external .R file, and then read the code into your Sweave file with the source() function.

For example, let’s say I have an R script saved as complexplot.R. I can include all of this code in an R chunk as follows:

Note: The code above will only work if the complexplot.R file is located in the same folder as my Sweave file. If the file is located somewhere else you’ll need to specify the full file path of the document (e.g.; file = “/Users/nphillips/Dropbox/Public/complexplot.R”)

8: Additional tips