Site icon R-bloggers

Sweave Tutorial 1: Using Sweave, R, and Make to Generate a PDF of Multiple Choice Questions

[This article was first published on Jeromy Anglim's Blog: Psychology and Statistics, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
In this post I present an example of using Sweave to prepare a PDF of formatted multiple choice questions.More broadly the example shows how to use Sweave to incorporate elements of a databaseinto a formatted LaTeX document.It aims to be useful to anyone wanting to learn more about the almost magical powers of make, Sweave, and R.

Overview

The repository with all source files is available at:

The repository allows you to download all files as an archive or view the files individually on the web.A copy of the final PDF generated from the process is available here

I ran the code on Windows with the following programs installed.

It should run on MAC and Linux with appropriate R, make, and LaTeX tools installed.

Assuming you have the above installed, to run the code

  1. Download the repository from github
  2. Uninstall to a directory
  3. Open the shell in that directory
  4. Type: make

The remainder of this post explains the code in each of the main files in the repository.


The Makefile

The makefile is used to build the PDF from the Rnw Source.It also performs other useful tasks.A copy of the makefile is shown below:

output = .output
rnwfile = Sweave_MCQ
backup = .backup

all:
    R CMD Sweave $(rnwfile).Rnw
    -mkdir $(output)
    -cp *.sty $(output)
    -mv *.tex *.pdf *.eps $(output)
    cd $(output); texify --run-viewer --pdf $(rnwfile).tex 

tex:
    cd $(output); texify --run-viewer --pdf $(rnwfile).tex

clean:
    -rm $(output)/*

backup:
    -mkdir $(backup)
    cp  $(output)/$(rnwfile).pdf $(backup)/$(rnwfile).pdf

I recently posted on the benefits of makefiles when developing Sweave documents.

The make file starts with three variables.

The file then has four goals.

The default goal is called all:.If make is called without argument from the command line in the project directory, the recipe immediately below all: is run. Note that all apparent indentations are tab indentations (a set of spaces would cause an error).

The tex: goal can be called by running make tex at the command line.I use it in case I want there is an error in the when compiling the pdf from the tex file.Sometimes its easier to work out where the bug is by manipulating the intervening tex file.Of course once the problem has been identified, it needs to be incorporated into the Rnw source.

The clean: goal removes all files in the output directory (i.e., all the derived files)

The backup: goal copies the resulting pdf into the backup folder.I figured this might be useful in order to include a copy of the final product in the repository.


.gitignore

/.output
.project

The .gitignore file prevents all files in the /.output directory (i.e., the derived files) and the file .project from being placed under version control in git.

I’m preparing a post on version control, git, and github which will be posted shortly.


Sweave_MCQ.Rnw

Sweave_MCQ.Rnw is the R noweb file that contains chunks of LaTeX and R code.When Sweave is run on this file, the R code chunks are converted into tex and, potentially, image files are generated.

LateX Preamble

\documentclass[12pt, a4paper]{exam}
\usepackage[OT1]{enc}
\usepackage{Sweave}
\SweaveOpts{echo=FALSE}
\usepackage{hyperref}            
\hypersetup{pdfpagelayout=SinglePage} % http://www.tug.org/applications/hyperref/ftp/doc/manual.html
\setkeys{Gin}{width=0.8\textwidth}
\pagestyle{headandfoot} % every page has a header and footer
\header{}{Sample Multiple Choice Questions}{}
\footer{}{Page \thepage\ of \numpages}{}

The latex preamble is mostly general code that ensures proper display of the reuslting document.

First R Code Chunk

<<prepare_data>>=
items <- read.csv("data/items.csv", stringsAsFactors = FALSE)

writeQuestion <- function(x){
    c("\\filbreak",
            paste("\\question\n", x["itemText"]),
            "\\begin{choices}",
            paste("\\choice", x["optionA"]),
            paste("\\choice", x["optionB"]),
            paste("\\choice", x["optionC"]), 
            paste("\\choice", x["optionD"]), 
            "\\vspace{10 mm}",
            "\\end{choices}\n\n")
}

itemText <- apply(items, 1, function(X)  writeQuestion(x = X))

answers <- paste(items$item, "=",
        LETTERS[as.numeric(items$correctAnswer)],
        sep ="")
answersText <- paste(answers, collapse = "; ")
@

Remaining code

\begin{questions}
<<print_items, results=tex>>=
cat(itemText, sep = "\n")
@
\newpage
\section*{Answers}
<<print_answers, results=tex>>=
cat(answersText) 
@

\end{questions}

Summary and Related Resources

The combination of make, R, Sweave, and LaTeX is tremendously powerful.Hopefully, this post encourages a few more people to have a play.To learn more check out some of the following posts and pages:

To leave a comment for the author, please follow the link and comment on their blog: Jeromy Anglim's Blog: Psychology and Statistics.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.