Sweave for a book

I have been using R for a long time, LaTeX for a while, and Sweave for less time, (all via Aquamacs) but I am struggling to write two books. This wiki is my attempt to crystallize and to share what I have learned from others (special thanks to B. Bolker, and F. Leisch).



Setup For A Book

I have a folder that contains

  • a master latex file, and
  • a folder for each chapter, one for front matter, one for appendices — in short, a folder for each manageable item(s).

Workflow

Here is what I do:

  1. Edit the .Rnw file …
  2. At the R > prompt, type > Sweave("myfile.Rnw") [that compiles the tex and R code, and makes graphics, etc.)
  3. I compile my master file (see next) myMaster.tex by clicking the little tex button in my Aquamacs toolbar. This builds the book, with the whole Table of Contents, and any chapters I want.

However, I am unhappy that I cannot figure out the graphics better. I think (see below) that I could do a better job using Sweave's technology.

Master Document

Here is a master doc I use. Note that I specify paths for graphics files using \graphicspath{ … } and use \includeonly to allow the correct table of contents when working on one particular chapter, and correct page numbers and figure and table nos. For instance, if I am working on chapter 5, I can compile just chapter five, and all figures will be number 5.1, 5.2, etc, and page numbers will reflect the number of pages in chaps 1-4 (e.g., chapter 5 is called chapter 5 — not chap 1 — and begins on page 148, not page 1).

\documentclass[envcountsame,envcountchap,oribibl]{svmono}
\usepackage{makeidx} % allows index generation
%%%%%%%%%%%%%%
%\usepackage{textcomp}
\usepackage[pdftex]{graphicx} % standard LaTeX graphics tool
% when including figure files
\usepackage{multicol} % used for the two-column index
\usepackage[bottom]{footmisc}% places footnotes at page bottom
\usepackage{amsmath}
\usepackage{float}
\usepackage{subfig}
\usepackage{paralist}
\usepackage{boxedminipage}
\usepackage{/Library/Frameworks/R.framework/Resources/share/texmf/Sweave}
%%%%%%%%%%%%%%%%
\makeindex % used for the subject index
% please use the style svind.ist with
% your makeindex program
\graphicspath{ {./figs/}{./Chap01/}{./Chap02/}{./Chap03/}{./Chap04/}{./Chap05/} }
\includeonly{Chap01/Chapter01b}
\includeonly{Chap02/Chapter02b}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}
\author{M. Henry H. Stevens}
\title{A Primer of Theoretical Population Ecology with R\{\small SPIN Springer's internal project number, if known} }
\subtitle{— Monograph —}
\maketitle
%%%%%%%%%%
\frontmatter%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\include{dedic}
%\include{BookProposalFrontMatter20060912}
\include{pref1}
\tableofcontents
%%%%%%%%%%%%
\mainmatter%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\include{part1}
\include{Chap01/Chapter01b}
\include{Chap02/Chapter02}
\include{Chap03DD/Chapter03060912}
\include{Chap04Meta/Chapter04060912}
\include{part2}
\include{Chap05/Chapter05b}
\include{Chap06/Chapter06b}
\include{part3}
\include{Chap07/Chapter07b}
\include{Chap08/Chapter08b}
\include{Chap09/Chapter09b}
\appendix
\include{Appendix/Appendixb}
%%%%%%%
\backmatter%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\include{solutions}
\include{referenc}
\printindex
%%%%%%%%%%
\end{document}

Each Chapter folder

Each chapter folder (e.g., for chapter 3) contains the .Rnw file, the .tex file that is compiled from the .Rnw, and all of the figures for that chapter (see note below about a path for figures in master doc).

The .Rnw file for each chapter has NO latex preamble, but begins with

{{\SweaveOpts{ eval=TRUE, prefix=FALSE, width=4, height=4, eps=FALSE, include=FALSE}
\chapter{titletext}
«echo=false, results=hide»=
setwd("~/…/Chap03")
rm(list=ls())
badfonts = FALSE
.detach.stuff = function() {
s1 = grep("package|Autoloads",search())
nattach = length(search())
xattach = search()[c(-1,-s1)]
for (i in xattach)
eval(substitute(detach(i),list(i=i)))
}
.detach.stuff()
## ps.options(family="NimbusSan")
ps.options(colormodel="cmyk")
options(width=65)
## palette(gray((0:8)/8))
library(lattice)
trellis.par.set(canonical.theme(color=FALSE))

@
This chapter covers … .}}

All the figures for each chapter (3-20 per chapter) accumulate in the chapter folder.

Making Figures

Sweave has an automated way for making .pdf and .eps graphics, but I don't understand it to well. It works kind of like

«myfig, fig=true»=
qqnorm(rnorm(100))

and this makes both an EPS and PDF graphic called myfile-myfig.pdf, where myfile.Rnw is the name of your file. You can use Sweave options to manipulate the prefix, and set the width, height, etc. but I don't know how to both include Sweave options in the chapter file, and still use the resulting .tex file in compiling the master doc.

You then put this in a graph as,

@
\begin{figure}[ht]
\centering
\includegraphics[width=.6\linewidth]{myfile1}
\caption{The species-abundance distribution resulting from …}
\label{fig:cssimhist}
\end{figure}

Another way of doing this is (and still including the code as part of the text), is

«myfig, include=false»=
qqnorm(rnorm(100))
@
\begin{figure}[ht]
\centering
«fig=true»=
«myfig»
@
\caption{The species-abundance distribution resulting from …}
\label{fig:cssimhist}
\end{figure}

The above uses the code specified in chunk "myfig."

The SweaveOpts at the beginning include include=FALSE because I did NOT want Sweave to "include" a copy of the figure automatically, but rather, allow me to put them in floats. Controlling width and height also allow me to make small figures by default (this helps make text large enough for the book).

Having Sweave make figures requires that the entire figure be made in one chunk. If you want to build a figure across multiple chunks, use


«echo=false, results=hide»=
quartz(, width=4, height=4.5»=
### Any other par statements here
«»=
qqnorm(rnorm(100))
«echo=false, results=hide»=
dev.print(pdf, "myfig.pdf")

I then include either the Sweave generated graphic, or the dev.print generated graphic in a float, e.g.,

@
\begin{figure}[ht]
\centering
\subfloat[With Rescue Effect]{%
\includegraphics[width=.47\linewidth]{myfile1.pdf} }
\subfloat[No rescue effect]{%
\includegraphics[width=.47\linewidth]{myfile2.pdf} }
\caption{The species-abundance distribution resulting from …..}
\label{fig:cssimhist}
\end{figure}

Tips for figures

Ben Bolker led me to a few key listserv emails including tips from Achim Zeileis, Mathias Templ, and Friedrich Leisch, from which I gleaned and/or quote the following:

The Sweave User Manual says (p. 12):
Attention: One thing that gets easily confused are the width/height parameters of the R graphics devices and the corresponding arguments to the LATEX \includegraphics command. The Sweave options width and height are passed to the R graphics devices, and hence affect the default size of the produced EPS and PDF files. They do not affect the size of figures in the document, by default they will always be 80% of the current text width.

Use \setkeys{Gin} to modify figure sizes or use explicit \includegraphics commands in combination with Sweave option include=FALSE.

To change the size of a particular .eps and .pdf fig:

«foo,fig=TRUE,height=4,width=8»=

@

To change the default size of figures in the latex document:


\setkeys{Gin}{width=0.75\textwidth}

This will change the default from this point on (so you could use this more than once).

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License