#+OPTIONS:    H:3 num:nil toc:2 \n:nil @:t ::t |:t ^:{} -:t f:t *:t TeX:t LaTeX:t skip:nil d:(HIDE) tags:not-in-toc
#+STARTUP:    align fold nodlcheck hidestars oddeven lognotestate hideblocks
#+SEQ_TODO:   TODO(t) INPROGRESS(i) WAITING(w@) | DONE(d) CANCELED(c@)
#+TAGS:       Write(w) Update(u) Fix(f) Check(c) noexport(n)
#+TITLE:      Org-babel-R
#+AUTHOR:     Eric Schulte, Dan Davison, Tom Dye
#+EMAIL:      schulte.eric at gmail dot com, davison at stats dot ox dot ac dot uk
#+LANGUAGE:   en
#+STYLE:      <style type="text/css">#outline-container-introduction{ clear:both; }</style>

#+begin_html
  <div id="subtitle" style="float: center; text-align: center;">
  <p>
  Org-babel support for
  <a href="http://www.r-project.org/">R</a>
  </p>
  <p>
  <a href="http://www.r-project.org/">
  <img src="http://www.r-project.org/Rlogo.jpg"/>
  </a>
  </p>
  </div>
#+end_html

* Notes                                                            :noexport:
** Template Design
  - What the user wants to know:
    - Required software
    - How to install it
    - How to configure it in Org-babel
    - Org-babel conventions that might affect the language
    - How it modifies Org-babel
    - Common ways to use it
** Queries
   - Eric, I think you should name your starter kit Literate Emacs
     Starter Kit (LESK).  I've taken the liberty of labeling the link
     to it that way below.  Is that OK?
   - I think LESK is a couple of steps away from being useful to Lisp
     illiterates (like me).  I'm thinking of LESK for Lisp
     IlliteraTEs, or LESK LITE.  Is that anathema?
 
** Comments
   - I'm not sure how you two use tags.  I've used :Fix on Dan's
     Graphical output, because I think it should be parceled out to
     various sections of the template, and not because I think it
     needs fixing in and of itself.

* Requirements                                                       :Update:
** [[http://ess.r-project.org/][Emacs Speaks Statistics]] 
   Required for session-based evaluation.
*** Installation using  [[http://github.com/eschulte/emacs-starter-kit/tree/master][Literate Emacs Starter Kit]]                    :noexport::Write:
    - unpack ess-VERSION.tgz in .emacs.d/src
    - for me, this created ess-5.6, need an alias named ess?
    - where to put (require 'ess-site)?
* Examples
  :PROPERTIES:
  :CUSTOM_ID: examples
  :END:
Examples demonstrating the use of R code within Org-mode.

- [[file:R/RBabelExample.org][RBabelExample]] ([[http://repo.or.cz/w/Worg.git/blob/HEAD:/org-contrib/babel/languages/R/RBabelExample.org][.org]], [[http://repo.or.cz/w/Worg.git/blob_plain/HEAD:/org-contrib/babel/languages/R/RBabelExample.pdf][.pdf]]) -- a short introductory example
- [[file:../uses.org::#foo][foo.org]] ([[http://repo.or.cz/w/Worg.git/blob_plain/HEAD:/org-contrib/babel/examples/foo.org][.org]], [[http://repo.or.cz/w/Worg.git/blob_plain/HEAD:/org-contrib/babel/examples/foo.pdf][.pdf]],  [[http://repo.or.cz/w/Worg.git/blob_plain/HEAD:/org-contrib/babel/examples/foo.org.html][preview]]) -- a more complex example

* Configuration in Org-babel				     :Write:noexport:
** Variables
* Language-specific Features 					      :Write:
** Graphical output 							:Fix:
    If a =:file filename.ext= header argument is provided to an R
    source block, then the output from the source block will go to the
    named file. What that output is depends on the value of the
    =:results= header argument.

    If the value is =:results graphics= then "base" graphics output is
    captured on disk, and a link to the graphics file is inserted into
    the Org-mode buffer (as is also the case with the graphics-only
    languages such as gnuplot, ditaa, dot, and asymptote.)  An attempt
    is made to find an R graphics device corresponding to the file
    extension.  Currently, the following extensions are recognized:
    .png, .jpg, .jpeg, .tiff, .bmp, .pdf, .ps, .postscript, and .svg.
    If the extension of the file name passed to =:file= is not
    recognized, png format output is created by default.
    

    For further clarification of =:file= and =:results=, see [[http://thread.gmane.org/gmane.emacs.orgmode/35396/focus=35766][this
    thread]].

# <<r-dev-header-args>>
    Additionally, values for several arguments to the R graphics
    device can be passed using header args:
    
#+begin_example 
    :width :height :bg :fg :units :pointsize :antialias :quality :compression :res :type :family
    :title :fonts :version :paper :encoding :pagecentre :colormodel :useDingbats :horizontal
#+end_example
    
    See the R help page for the graphics devices (e.g. using =?png=,
    =?pdf=) for explanations of these arguments.

    Arguments to the R graphics device can also be passed as a string
    in R argument syntax, using the header arg =:R-dev-args=.  This is
    useful for graphics device arguments that don't have an Org-babel
    header argument counterpart.
    
    The following example source block illustrates use of
    =:R-dev-args= to pass background and foreground colors.  Note that
    both of these arguments can also be passed directly as
    header args, using =:fg= and =:bg=.

#+begin_src org
  ,#+header: :width 8 :height 8 :R-dev-args bg="olivedrab", fg="hotpink"
  ,#+begin_src R :file z.pdf :results graphics
  ,plot(matrix(rnorm(100), ncol=2), type="l")
  ,#+end_src
#+end_src

If "base" graphics aren't begin generated, then additional header
arguments might be needed.  For example, with the =ggplot2= package,
graphics output requires =:results output graphics=.  The following
example writes the graphics output to the file specified in the
=:file= header argument.

#+begin_example
  ,#+srcname: r-edge-angle-histogram
  ,#+begin_src R :results output graphics :var x=whole-adzes :file r/adze_edge_angle.png :width 400 :height 300
    library(ggplot2)
    adze.edge.angle <- ggplot(x, aes(edge_angle))
    adze.edge.angle + geom_histogram(aes(y=..density..)) +
    geom_density(weight=2) + xlab("Measured cutting edge angle (degrees)")
  ,#+end_src
  
  ,#+results:
  [[file:r/adze_edge_angle.png]]
#+end_example

** Missing Values					     :Write:noexport:
* Additions to Org-babel                                              :Write:
** Header Arguments
R support introduces a large number of header arguments to Org-babel.
Most of these set parameters of R graphic devices, as described [[r-dev-header-args][above]].

It is also possible to include column names during export of data
frames.

| Header arg    | Meaning                        |
|---------------+--------------------------------|
| :colnames yes | Include column names in output |

* Common Idioms						     :Write:noexport:
* Tips for usage
** Debugging
   This section contains some tips on how to proceed if your R code is
   not doing what you had hoped.
*** Use =:session=
    Evaluate your code using the =:session= header argument, then
    visit the R buffer (i.e. the buffer containing the "inferior ESS"
    process). Then you can inspect the objects that have been created,
    and try out some lines of code. Useful R functions for inspecting
    objects include (as always in R, type a "?" followed by the name
    of the function to get help with the function)
    - str
    - dim
    - summary
*** Use ESS to step through evaluation line-by-line
    1. Use C-c ' to visit the edit buffer for your code block
    2. Use ess-eval-line-and-step to evaluate each line in turn

In addition to ess-eval-line-and-step, there are several other ESS
functions with names beginning ess-eval-*. They evaluate lines and
regions in different ways; it's worth looking at their descriptions
(C-h f).
    
** LaTeX code from R
This example summarises a linear regression fit. Usually the org-babel
user should not have to be involved in latex code generation, as this
is the responsibility of org-mode's latex export engine. But in this
example, neither the printed representation nor the value of
summary(lm(y ~ x)) is at all tabular, and it would therefore require
some work to get the information in to an org table. However, the
xtable package can be used to output a latex table. Using ':results
latex' in org-babel ensures that this is stored as a latex block in
the org buffer and thus can be included correctly in latex-based
export targets.

#+begin_src R :results output latex
library(xtable)
x <- rnorm(100)
y <- x + rnorm(100)
xtable(summary(lm(y ~ x)))
#+end_src

#+results:
#+BEGIN_LaTeX
% latex table generated in R 2.9.2 by xtable 1.5-5 package
% Wed Dec  9 17:17:53 2009
\begin{table}[ht]
\begin{center}
\begin{tabular}{rrrrr}
  \hline
 & Estimate & Std. Error & t value & Pr($>$$|$t$|$) \\ 
  \hline
(Intercept) & -0.0743 & 0.0969 & -0.77 & 0.4454 \\ 
  x & 1.0707 & 0.0923 & 11.60 & 0.0000 \\ 
   \hline
\end{tabular}
\end{center}
\end{table}
#+END_LaTeX
** Org output from R
David Hajage's [[http://cran.r-project.org/web/packages/ascii/index.html][ascii]] R package creates appropriate plain text
representations of many R objects, and features an option to specify
that the plain text representations should be in Org format. This can
be particularly useful for retrieving non-tabular R data structures in
Org.

In R:
#+begin_example 
> library(ascii)
> options(asciiType = "org")
> library(Hmisc)
> ascii(describe(esoph))
#+CAPTION: esoph
- 5 Variable
- 88 Observations

*agegp*
|  n | missing | unique |
| 88 |       0 |      6 |

|           | 25-34 | 35-44 | 45-54 | 55-64 | 65-74 | 75+ |
| Frequency |    15 |    15 |    16 |    16 |    15 |  11 |
| %         |    17 |    17 |    18 |    18 |    17 |  12 |

*alcgp*
|  n | missing | unique |
| 88 |       0 |      4 |

 0-39g/day (23, 26%), 40-79 (23, 26%), 80-119 (21, 24%), 120+ (21, 24%)

*tobgp*
|  n | missing | unique |
| 88 |       0 |      4 |

 0-9g/day (24, 27%), 10-19 (24, 27%), 20-29 (20, 23%), 30+ (20, 23%)

*ncases*
|  n | missing | unique |  Mean | .05 | .10 | .25 | .50 | .75 | .90 | .95 |
| 88 |       0 |     10 | 2.273 | 0.0 | 0.0 | 0.0 | 1.0 | 4.0 | 5.3 | 6.0 |

|           |  0 |  1 |  2 |  3 | 4 | 5 | 6 | 8 | 9 | 17 |
| Frequency | 29 | 16 | 11 |  9 | 8 | 6 | 5 | 1 | 2 |  1 |
| %         | 33 | 18 | 12 | 10 | 9 | 7 | 6 | 1 | 2 |  1 |

*ncontrols*
|  n | missing | unique |  Mean | .05 | .10 | .25 | .50 |  .75 |  .90 |  .95 |
| 88 |       0 |     30 | 11.08 | 1.0 | 1.0 | 3.0 | 6.0 | 14.0 | 29.1 | 40.0 |

 lowest:  1  2  3  4  5, highest: 40 46 48 49 60
#+end_example


 From Org-babel:
#+begin_src R :results output org
  library(ascii)
  options(asciiType="org")
  ascii(summary(table(1:4, 1:4)))
#+end_src

#+results:
Loading required package: proto
- Number of cases in table: 4 
- Number of factors: 2 
- Test for independence of all factors:
  - Chisq = 12, df = 9, p-value = 0.2133
  - Chi-squared approximation may be incorrect

** ess-switch-to-end-of-ESS
   When in an org mode R code edit buffer with an associated R
   session, ess-switch-to-end-of-ESS will bring the R session buffer
   into view and place point at the prompt. ESS binds this to C-c C-z
   and C-M-r by default.
