#+TITLE: Key features of org-babel with R
#+AUTHOR: Stephen Eglen
#+STARTUP: hideblocks

# Note that at the top of the file we can set some system-wide
# preferences, which can in principle be overriden further down in the
# document, e.g. we could specify by default that no results are output
# using the line `#+BABEL: :results silent'



* Prelim:

#+begin_src emacs-lisp
(setq org-src-fontify-natively t)
#+end_src


* Why Sesssion?

- You can see what is happening, rather than running in batch.

- A bit quicker than starting a new session each time?

- state kept from one block to another

Example from http://orgmode.org/worg/org-contrib/babel/intro.html

* Take input from an org table
  #+tblname: examscores
  | name  | maths | physics |
  | joe   |    75 |      90 |
  | fred  |    80 |      50 |
  | harry |    90 |      20 |

What we would like to do now is to process this simple table so that
we compute the weighted average for the score.  We will weight the total
slightly in favour of physics.


TODO  compute mean.

* Passing results from one language to another via org.

We can have code snippets in different languages, and plug them
together using the textual output from one code block.  Here is a
simple example where we take some output from a shell command and feed
it into an R block.  (Of course, this example can be done entirely in
R ...)

** Generate some output from the shell

Here we just find the top ten files.
#+begin_src sh :exports both 
  ls | head -10
#+end_src
   
#+results:
| RBabelExample     |
| RBabelExample.pdf |
| RBabelExample.tex |
| auto              |
| babel-sources.org |
| cise2011          |
| drift.org         |
| fig2.pdf          |
| fishlevels.pdf    |
| foo               |

** Feed it into R.

#+begin_src R 
round(runif(n=5, min=0, max=1), 3)
#+end_src

#+results:
| 0.435 |
| 0.884 |
| 0.219 |
| 0.748 |
| 0.532 |

   
* Directly calling R within a paragraph.

Let's say you want to find out what \pi/2 is.  Just ask R to evaluate
it for you inline like this: \pi/2 = src_R{signif(pi/2, 8)} to 8
significant digits.  Note how Org mode knows automatically what you
mean when you type =\pi=, so you don't need to go into `math mode'
like you would in latex.  Obviously for more complicated math you can.


* Comparing base vs lattice graphics output

Unfortunately you need to have slightly different expressions for
generating base and lattice graphics output.

** Example of lattice graphics output

When using lattice graphics, you will need to set =:results output
graphics= rather than just =:results graphics:=.  For example, here we
generate a contour plot of the function

\[ \log F - F + \log S - S = k \]

where F and S are varied to see what the constant k should be.  Note
that we export the code, rather than exporting both the code and the
results (in this case the graphics).  The results line is still output
though (delete it to check).  However, note that the caption line must
come before the file: line.


#+begin_src R :exports code :results output graphics :file fishlevels.pdf
library(lattice)
f <- seq(from=0.1, to=4, length=100)
s <- f
grid <- expand.grid(x=f, y=s)
grid$z <- log(grid$x) - grid$x + log(grid$y) - grid$y
levelplot(z ~ x + y, grid, more=TRUE, contour=TRUE,xlab='fish', ylab='shark')
#+end_src

#+caption: Contour plot generated by lattice graphics, showng how populations of sharks and fish vary.
#+results:
[[file:fishlevels.pdf]]


* Passing from one language to another:

First of all we use a shell command to find the first five largest
files in the currenr directory.
#+srcname: biggest-files
#+begin_src sh :exports both :results replace
  ls -sS | grep -v total | head -5 
#+end_src

#+results: biggest-files
| 1112 | ob-R-examples.pdf |
|  752 | fishlevels.pdf    |
|  240 | RBabelExample.pdf |
|   56 | pie.png           |
|   40 | babel-sources.org |

This table is labelled, and can be passed to an R function to create
a little pie chart:

#+srcname: directory-pie-chart(f = biggest-files)
#+begin_src R :exports both :file pie.png :results graphics
  pie(f[,1], labels = f[,2])
#+end_src

#+caption: Relative sizes of different files in current directory.
#+results: directory-pie-chart
[[file:pie.png]]


#+begin_src R
 x <- numeric(4)
 x[1] <- 10
#+end_src


* Sources

http://orgmode.org/worg/org-contrib/babel/languages/ob-doc-R.html

The main documentation page.  Many examples adapted from here or other
Org Babel (OB) pages.

* Things to do:
** TODO how to clear out old results?

** Nicer table formattting using xtable() or other packages.

*** The ascii package

The ascii package in R allows you to output R objects in a way that
can be directly interpreted by org mode. 
#+begin_src R :results output org
  library(ascii)
  ascii(esoph, type="org")
#+end_src

#+results:
#+END_ORG
#+BEGIN_ORG
#+END_ORG
#+BEGIN_ORG


* Defining simple functions and inline calls

Here is an example taken from the release notes of Org 7.6.  We first define
a function, also showing that variables can take default values.
Argument interpretation *seems* similar to that used by R.  It is
defined here in lisp, but the same principle applies to R functions.

#+source: minus
#+begin_src emacs-lisp :var a=0 :var b=2
  (- a b)
#+end_src

We then call the function directly as in the following ways

#+call: minus(a=8, b=4)

#+call: minus(9)

Or we can call the function inline, as follows, e.g. to check that
call_minus(a=13, b=7) is the answer to 13-7.  To call a function
inline, simply prefix the function name by =call_=.
