R, RStudio, knitr, apa6, citations and LaTeX minimal working example

Nota bene: Original post thrown up quickly to promote usage. Some helpful edits have been made, but as usual, continue at your own risk.

I detest copy-pasting analysis results (laziness is a virtue), so my current statistical analysis workflow uses the knitr package to convert results from R into a LaTeX file and then into a PDF report (by pressing one button). After months of using this power only for Beamer presentations and statistics homework assignments, I’ve figured out how to add the apa6 package and automatic bibliography generation to the process for building a reproducible manuscript. This post shares the framework, in hopes that free some readers of the torture that is copy-pasting from SPSS to Excel to Word–and then needing to update the analysis.

How does this work?

In RStudio, I have set my Sweave options (in Tools > Global Options) to “Weave Rnw files using: knitr.” With this setting, I simply open up the RNW file of interest, and work as desired.

RNW files have both TeX and R commands in them–but the R commands are encased in “chunks” and one must run one an R package (either knitr, or its predecessor, Sweave) on the RNW file to create a TEX file that can then be compiled as normal. Luckily, RStudio has a “compile PDF” button when you are editing RNW files, make that RNW->TEX->PDF conversion a one-click process (assuming you have no debugging to do). What increases the one-click fun potential is that in the RNW file I can include all of my normal LaTeX bells and whistles, including citations and automatic bibliographies.

(If you are unfamiliar with anything I’ve mentioned, there are many existing resources for R, knitr, and LaTeX, I would recommend becoming comfortable with R and LaTeX separately, then taking on their combination through knitr.)

What is the example?

I have created a short example RNW file (code shown below, and also available as  a file version here). The code uses a “references.bib” file. I’ve also uploaded a .zip archive with the .rnw, .bib, and three .pdf examples. These PDF examples are the document compiled in the three different modes available from the apa6 package: manuscript mode, document mode, and (a semi-broken/buggy) journal mode.

\documentclass[man]{apa6} % man for manuscript format, jou for journal format, doc for standard LaTeX document format
\usepackage[natbibapa]{apacite} % Divine intervention help you if you need to use a different citation package.
\usepackage[american]{babel}
\usepackage[utf8]{inputenc}
\usepackage{csquotes}

\usepackage{url}   % this allows us to cite URLs in the text
\usepackage{graphicx}   % allows for graphic to float when doing jou or doc style
\usepackage{verbatim}   % allows us to use \begin{comment} environment
\usepackage{caption}
%\usepackage{lscape}
\usepackage{pdflscape}

\title{Minimal Working Example of RStudio-Friendly Knitr and apa6 Files}
\shorttitle{Knitr and apa6}

% Based off of code provided in a question by Melvin Roest on tex.stackexchange.com
% (http://tex.stackexchange.com/questions/176745/strange-knitr-behavior-with-apa6-class-manuscript)
\author{Author Name}
\affiliation{Department of Intellectual Inquiry \\ Carnegie Mellon University}

% apa6 uses different calls for more than one author, example

%\twoauthors{Student T. Stat}{Committee:}
%\twoaffiliations{Department of Wheat-Based Yeast Products \\ Carnegie Mellon University}{Advisor Awesome (chair), Committe Member 2, Committee Member 3}

%\rightheader{knitr and apa6} % for jou format
\leftheader{LastName}

\authornote{Acknowledgements here. Because you know you didn't do this alone.}
\note{\today}

\journal{} %\journal{Fictional Journal of Awesome} % for jou format
\volume{} %\volume{5,1,5-10}% Volume, number, pages; typeset in the top left header in jou and doc modes, underneath the content of %\journal

\keywords{minimal working example, manuscript, apa6}

\abstract{Abstract here. 95 words left.}

\ccoppy{} %\ccoppy{Copyright notice, etc.; typeset in the top right header of page 1 (jou and doc modes only)}

\begin{document}

\maketitle

<<setup, include=FALSE, cache=FALSE>>=
#library(knitr)

# set working directories
analysis.directory <- "C:/.../data_analysis/"
jul2014.data.directory <- "C:/.../data/data_JUL/"
output.directory <- "C:/.../manuscript/"
setwd(output.directory)

# set global chunk options, put figures into folder
opts_chunk$set(fig.path='figures/figure-', fig.align='center', fig.show='hold')
options(replace.assign=TRUE,width=75)

# save workspace image, if you want
#the.date >=
require(ggplot2)
#require(plyr)

# load datasets here
#setwd(jul2014.data.directory)
#my.df >=
# note: I use fig.width, fig.height, and out.width to resize figures the way I want them. Your mileage may vary.
sample.n <- 100; x <- c(1:sample.n)/2; y <- x + rnorm(sample.n,0,2)
df.a <- data.frame(y=y,x=x,treat=factor(rep(c(0,1),each=(sample.n/2)),
                   labels=c("control","treatment")))
a.lmfit.t0 <- lm(y ~ x, data=subset(df.a,treat=="control"))
a.lmfit.t1 <- lm(y ~ x, data=subset(df.a,treat=="treatment"))
ggplot(df.a,aes(x=x,y=y,group=treat)) + geom_point(aes(shape=treat),
  size = 4) + scale_shape_manual(values=c(19,1)) + ggtitle(
  "No T effect") + geom_abline(intercept=coef(a.lmfit.t0)[1],
  slope=coef(a.lmfit.t0)[2],col="red",linetype="dashed",lwd=1) + geom_abline(
  intercept=coef(a.lmfit.t1)[1],slope=coef(a.lmfit.t1)[2],
  col="blue",linetype="solid",lwd=0.5)
@
\end{center}
\end{figure} 

Also, you can still print code chunks:
<<codechunk, include=FALSE,echo=TRUE,cache=TRUE>>=
x <- 3
y <- 4
print(x + y)
@

\section{General Discussion}

\bibliographystyle{apacite}
\bibliography{references}

\end{document}

Happy dynamic report creation.

2 thoughts on “R, RStudio, knitr, apa6, citations and LaTeX minimal working example

  1. Hi there!

    I am trying to write a paper in my R-studio session with Sweave. I followed your example and I got the same result:
    Line 1 LaTeX error: File `apa6.cls’ not found
    ==> Fatal error occurred, no output PDF file produced!

    I also want to say that I included the apa6.cls file in the same directory where I am saving the .Rnw file…

    1. Hi Juan,

      I just checked this: I can download apa6 as a package through the Package Manager of my LaTeX distribution (I use MikTeX). This way it is automatically accessed by my distribution on that particular computer and does not need to be included in every project file. I’m certain there is a way to compile/utilize a .CLS (or .STY) file included in a project folder (which may help if you do not have admin privileges for installing on a computer), but to get moving forward (i.e., you need to write the paper sooner rather than later), I would recommend just going through the Package Manager, so you can spend more time on the paper’s content.

      Good luck!
      Erin

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>