% Created 2011-08-01 Mon 10:17
\documentclass[11pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{fixltx2e}
\usepackage{graphicx}
\usepackage{longtable}
\usepackage{float}
\usepackage{wrapfig}
\usepackage{soul}
\usepackage{textcomp}
\usepackage{marvosym}
\usepackage{wasysym}
\usepackage{latexsym}
\usepackage{amssymb}
\usepackage{hyperref}
\tolerance=1000
\usepackage{amscd}
\providecommand{\alert}[1]{\textbf{#1}}

\title{An Org-mode Demo}
\author{Eric Schulte}
\date{\today}

\begin{document}

\maketitle


  \hypersetup{
    linkcolor=blue,
    pdfborder={0 0 0 0}
  }
  %%SJE: this broken?
  %%\lstset{basicstyle=\ttfamily\bfseries\small}

\section*{Introduction}
\label{sec-1}

\begin{center}
Adapted from \emph{\href{http://www.stat.umn.edu/~charlie/Sweave/foo.Rnw}{An Sweave Demo}} by Charles J. Geyer.
\end{center}

This is a demo for using Org-babel to produce \LaTeX{} documents with
embedded R code.  To get started fire up Emacs and create a text file
with the \texttt{.org} suffix.  You should see Org-mode become your major
mode -- denoted by \texttt{Org} in your status bar.

Press \texttt{C-c C-e} while viewing this Org-mode buffer and you will see a
menu appear with options for export to a variety target formats --
herein we'll only consider export to \LaTeX{}.

So now we have a more complicated file chain
$$
\begin{CD}
   \texttt{foo.org}
   @>\texttt{Org-mode}>>
   \texttt{foo.tex}
   @>\texttt{latex}>>
   \texttt{foo.dvi}
   @>\texttt{xdvi}>>
   $view of document$
\end{CD}
$$
and what have we accomplished other than making it twice as annoying
to the WYSIWYG crowds (having to use both \texttt{Org-mode} and \texttt{latex} to get
anything that looks like the document)?

Well, we can now include \texttt{R} in our document.  Here's a simple example

\begin{verbatim}
2 + 2
\end{verbatim}




\begin{verbatim}
 4
\end{verbatim}



What I actually typed in \texttt{foo.org} was
\begin{verbatim}
 #+begin_src R :exports both
   2 + 2
 #+end_src
\end{verbatim}


This is a ``code block'' to be processed by Org-babel.  When Org-babel
hits such a thing, it processes it, runs R to get the results, and
stuffs the output in the \LaTeX{} file it is creating.  The \LaTeX{} between
code chunks is copied verbatim (except for in-line src code, about
which see below).  Hence to create a \emph{active} document you just write
plain old text interspersed with ``code blocks'' which are plain old R.

\pagebreak[3]

Plots get a little more complicated.  First we make something to plot
(simulated regression data).

\begin{verbatim}
n <- 50
x <- seq(1, n)
a.true <- 3
b.true <- 1.5
y.true <- a.true + b.true * x
s.true <- 17.3
y <- y.true + s.true * rnorm(n)
out1 <- lm(y ~ x)
summary(out1)
\end{verbatim}







\begin{verbatim}
 
Call:
lm(formula = y ~ x)

Residuals:
    Min      1Q  Median      3Q     Max 
-33.373 -14.674  -3.277  13.418  49.543 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)  11.4367     5.6781   2.014   0.0496 *  
x             1.3418     0.1938   6.924 9.63e-09 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 

Residual standard error: 19.77 on 48 degrees of freedom
Multiple R-squared: 0.4997,     Adjusted R-squared: 0.4893 
F-statistic: 47.94 on 1 and 48 DF,  p-value: 9.626e-09
\end{verbatim}




Figure \ref{fig:one} (p. \pageref{fig:one}) is produced by the following code

\begin{verbatim}
plot(x, y)
abline(out1)
\end{verbatim}



Note that \texttt{x}, \texttt{y}, and \texttt{out1} are remembered from the preceding code
chunk.  We don't have to regenerate them.  All code chunks are part of
one R ``session''.


\begin{figure}[p]
\centering
\includegraphics[width=0.8\textwidth,]{fig1.pdf}
\caption{\label{fig:one}Scatter Plot with Regression Line}
\end{figure}

Now this was a little tricky.  We did this with two code chunks,
one visible and one invisible.  First we did
\begin{verbatim}
 #+srcname: fig1plot
 #+begin_src R :exports code :file fig1plot.pdf
   plot(x, y)
   abline(out1)
 #+end_src
\end{verbatim}

where the \texttt{:exports code} indicates that only the return value (not
code) should be exported and the \texttt{\#+srcname: fig1plot} gives the code
block a name (to be used later).  And ``later'' is almost immediate.
Next we did
\begin{verbatim}
 #+source: fig1
 #+begin_src R :exports results :noweb yes :file fig1.pdf :results graphics
   <<fig1plot>>
 #+end_src
\end{verbatim}


In this code block the \texttt{:file fig1.pdf} header argument indicates that
the block generates a figure.  Org-babel automagically makes a PDF
file for the figure, and Org-mode handles the export to \LaTeX{}.  The
\texttt{<<fig1plot>>} is an example of ``code block reuse''.  It means that we
reuse the code of the code chunk named \texttt{fig1plot}.  The \texttt{:exports results} in the code block means just what it says (we've already seen
the code---it was produced by the preceding chunk---and we don't want
to see it again, we only want to see the results).  It is important
that we observe the DRY/SPOT rule (\emph{don't repeat yourself} or \emph{single point of truth}) and only have one bit of code for generating the
plot.  What the reader sees is guaranteed to be the code that made the
plot.  If we had used cut-and-paste, just repeating the code, the
duplicated code might get out of sync after edits.  The rest of this
should be recognizable to anyone who has ever done a \LaTeX{} figure.

So making a figure is a bit more complicated in some ways, but much simpler
than others.  Note the following virtues
\begin{itemize}
\item The figure is guaranteed to be the one described by the text (at
  least by the R in the text).
\item No messing around with sizing or rotations.  It just works!
\end{itemize}



Note that if you don't care to show the R code to make the figure, it
is simpler still.  Figure \ref{fig:two} shows another plot.  What I
actually typed in \texttt{foo.org} was
\begin{verbatim}
 #+srcname: fig2
 #+begin_src R :exports results :file fig2.pdf :results graphics
   out3 <- lm(y ~ x + I(x^2) + I(x^3))
   plot(x, y)
   curve(predict(out3, newdata=data.frame(x=x)), add = TRUE)
 #+end_src
\end{verbatim}


\begin{figure}[p]
\centering
\includegraphics[width=0.8\textwidth,]{fig2.pdf}
\caption{\label{fig:two}Scatter Plot with Cubic Regression Curve}
\end{figure}
\pagebreak

Now we just excluded the code for the plot from the figure (with
\texttt{:exports results} so it doesn't show).

Also note that every time we re-export Figures \ref{fig:one}
and \ref{fig:two} change, the latter conspicuously (because the
simulated data are random).  Everything just works.  This should tell
you the main virtue of Org-babel.  It's always correct.  There is
never a problem with stale cut-and-paste.



Simple numbers can be plugged into the text with the \texttt{src\_R} command,
for example, the quadratic and cubic regression coefficients in the
preceding regression were $\beta_2$ =  \texttt{0.132}
and $\beta_3$ =  \texttt{-0.0014}.  Just magic!  What I
actually typed in \texttt{foo.org} was


\begin{verbatim}
were $\beta_2$ = src_R{round(out3$coef[3], 4)}
and $\beta_3$ = src_R{round(out3$coef[4], 4)}
\end{verbatim}




The \texttt{xtable} command is used to make tables.  (The following is the
Org-babel output of another code block that we don't explicitly show.
Look at \texttt{foo.org} for details.)

\begin{verbatim}
out2 <- lm(y ~ x + I(x^2))
foo <- anova(out1, out2, out3)
foo
\end{verbatim}





\begin{verbatim}
 X11cairo 
       2
 I(x^2) 
 0.132
 I(x^3) 
-0.0014
 Analysis of Variance Table

Model 1: y ~ x
Model 2: y ~ x + I(x^2)
Model 3: y ~ x + I(x^2) + I(x^3)
  Res.Df   RSS Df Sum of Sq      F  Pr(>F)  
1     48 18770                              
2     47 17708  1   1061.93 2.8462 0.09836 .
3     46 17163  1    545.39 1.4618 0.23283  
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
\end{verbatim}




\begin{verbatim}
class(foo)
\end{verbatim}




\begin{verbatim}
 [1] "anova"      "data.frame"
\end{verbatim}



\begin{verbatim}
dim(foo)
\end{verbatim}




\begin{verbatim}
 [1] 3 6
\end{verbatim}



\begin{verbatim}
foo <- as.matrix(foo)
foo
\end{verbatim}




\pagebreak



 % latex table generated in R 2.13.0 by xtable 1.5-6 package
% Mon Aug  1 10:17:07 2011
\begin{table}[ht]
\begin{center}
\begin{tabular}{rrrrrrr}
  \hline
 & Res.Df & RSS & Df & Sum of Sq & F & Pr($>$F) \\ 
  \hline
1 & 48 & 18770.04 &  &  &  &  \\ 
  2 & 47 & 17708.11 & 1 & 1061.93 & 2.846 & 0.098 \\ 
  3 & 46 & 17162.72 & 1 & 545.39 & 1.462 & 0.233 \\ 
   \hline
\end{tabular}
\caption{ANOVA Table}
\label{tab:one}
\end{center}
\end{table}

\begin{verbatim}
   Res.Df      RSS Df Sum of Sq        F     Pr(>F)
 1     48 18770.04 NA        NA       NA         NA
 2     47 17708.11  1 1061.9286 2.846210 0.09836065
 3     46 17162.72  1  545.3886 1.461765 0.23282729
\end{verbatim}


So now we are ready to turn the matrix \texttt{foo} into Table \ref{tab:one}
using the R chunk
\begin{verbatim}
 #+begin_src R :results output latex :exports results
   library(xtable)
   xtable(foo, caption = "ANOVA Table", label = "tab:one",
       digits = c(0, 0, 2, 0, 2, 3, 3))
 #+end_src
\end{verbatim}


(note the difference between arguments to the \texttt{xtable} function and to
the \texttt{xtable} method of the \texttt{print} function)

To summarize, Org-babel is terrific, so important that soon we'll not
be able to get along without it.  Its virtues are
\begin{itemize}
\item The numbers and graphics you report are actually what they
  are claimed to be.
\item Your analysis is reproducible.  Even years later, when you've
  completely forgotten what you did, the whole write-up, every single
  number or pixel in a plot is reproducible.
\item Your analysis actually works---at least in this particular instance.
  The code you show actually executes without error.
\item Toward the end of your work, with the write-up almost done you
  discover an error.  Months of rework to do?  No!  Just fix the error
  and re-export.  One single problem like this and you will have all
  the time invested in Org-babel repaid.
\item This methodology provides discipline.  There's nothing that will make
  you clean up your code like the prospect of actually revealing it to
  the world.
\end{itemize}

Whether we're talking about homework, a consulting report, a textbook,
or a research paper.  If they involve computing and statistics, this
is the way to do it.

\end{document}