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

* Introduction

  This is an example document to demonstrate some simple R blocks in
  an org document.  Convert it either to pdf or html using the
  appropriate export tools.

** Prelim:

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


** Getting started

   Here we compare the output from =:results value= with =:results
   output=.  Within each code block, press =C-c C-c= to see (or update)
   the results.  

   #+begin_src R :results value :exports both
     1 + 2
     3 + 4
   #+end_src


   #+begin_src R :results output :exports both
     1 + 2
     3 + 4
   #+end_src


* Process an org table in R

  We use org-mode to create a nice-looking table, which we want to
  process in R.

  #+tblname: examscores
  | name  | maths | physics |
  |-------+-------+---------|
  | joe   |    75 |      90 |
  | fred  |    80 |      50 |
  | harry |    90 |      75 |


** Process the results

   We would like to read in the table, and then compute the weighted
   sum of the scores for each student.  Note how we refer to the table
   above through its /tblname/.

   #+srcname: process-exams(scores = examscores)
   #+begin_src R :results output :exports both
     ave <- (0.7 * scores$maths) + (0.3 * scores$physics)
     data.frame(name=scores$name, score=ave)
   #+end_src

   
* 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 base graphics output

   With base graphics, e.g. to make a histogram, try the following
   snippet.  Here we generate a png file, just hit =C-c C-c= within
   the code to eval it, and generate the resulting file.

   #+begin_src R :exports both :results graphics :file hist.png
     hist( rnorm(1e4))
   #+end_src


   Emacs can view png's within a buffer, and even show them inline
   using the minor mode =iimage-mode=.  Turn this on with =M-x
   turn-on-image-mode=.  (Warning: this sometimes places the images in
   the wrong place.)


** 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.

   #+caption: Lattice contour plot showing populations of sharks and fish.
   #+begin_src R :exports both :results output graphics :file fishlevels.png
     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


* 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 ...)


  #+srcname: biggest-files
  #+begin_src sh :exports both :results replace
  ls -sS /etc | grep -v total | head -5
  #+end_src




  This table is named /biggest-files/, which 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.

* 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_=.


* Why :session?

  We have not used :session here in the calls, for simplicity.  But you
  might find it useful, for several reasons.

  - 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 in the process.

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


* 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:							   :noexport:
** TODO how to clear out old results?
   org-babel-kill-results post 7.7, =C-c C-v k=

   #+begin_src emacs-lisp :eval no
     (org-babel-kill-results 'kill-all)
   #+end_src

** Nicer table formattting using xtable() or other packages.
  #+begin_src R :export both :results output
  library(ascii)
  print(ascii(esoph, type="org"))
  #+end_src


   
