1 #+OPTIONS: H:3 num:nil toc:t \n:nil @:t ::t |:t ^:t -:t f:t *:t TeX:t LaTeX:t skip:nil d:(HIDE) tags:not-in-toc
2 #+STARTUP: align fold nodlcheck hidestars oddeven lognotestate
3 #+SEQ_TODO: TODO(t) INPROGRESS(i) WAITING(w@) | DONE(d) CANCELED(c@)
4 #+TAGS: Write(w) Update(u) Fix(f) Check(c)
5 #+TITLE: org-R: Computing and data visualisation in Org-mode using R
7 #+EMAIL: davison@stats.ox.ac.uk
10 #+CATEGORY: worg-tutorial
12 # #+INFOJS_OPT: view:overview
14 [[file:../index.org][{Back to Worg's index}]]
17 org-R is an org-mode extension that performs numerical computations
18 and generates graphics. Numerical output may be stored in the org
19 buffer in org tables, and the input can also come from an org
20 table. Rather than starting off by documenting everything
21 systematically, I'll provide several commented examples. Towards the
22 end there are lists of [[*Table of available actions][available actions]] and [[*Table of available options][other options]].
24 Although, behind the scenes, it uses [[http:www.r-project.org][R]], you do not need to know
25 anything about R. Common operations are provided `off the shelf' by
26 specifying options on lines starting with #+R:. Having said that,
27 org-R also accepts raw R code (#+RR: lines). For those who don't
28 yet know R, but think they might be interested, try the showcode:t
29 option. It displays the R code corresponding to the action you
30 requested, and so provides a good starting point for fine-tuning
31 your analysis. But that's getting ahead of things.
33 My hope is, of course, that this will be of use to people. So at
34 this stage any comments, ideas, feedback, bug reports etc would be
35 very welcome. I'd be happy to help anyone that's interested in
36 using this, via the Org mailing list.
38 If you'd like to try out these commands yourself, the Org file that
39 created this web page is @<a href="org-R.org">here@</a>.
42 The code is currently [[http://www.stats.ox.ac.uk/~davison/software/org-R/org-R.el][here]] Soon it will be in the contrib
43 directory. The other things you need are R (Windows / OS X binaries
44 available on the [[http://www.r-project.org][R website]] widely available in linux package
45 repositories) and the emacs mode [[http://ess.r-project.org/][Emacs Speaks Statistics]] (ESS). ESS
46 installation instructions are [[http://ess.r-project.org/Manual/readme.html#Installation][here.]] Personally, under linux, I have
49 #+BEGIN_SRC emacs-lisp
50 (add-to-list 'load-path "/path/to/ess/lisp")
55 org-R uses two different option lines to specify an
56 analysis/plot: #+R: and #+RR:. #+RR: is the one that
57 accepts R code, so we'll ignore that for now. To make the action
58 happen, use M-x org-R-apply with point in the #+R:
59 line. That's the only function you need, and it would make sense to
60 bind it to some key. So, first example.
62 * Computing on org tables: tabulating values
63 Here's a command to tabulate the values in the second column. Issue
64 M-x org-R-apply in the following #+R line.
73 #+R: action:tabulate columns:2
88 . So the values in column 2 were tabulated as requested. However,
89 the original data got overwritten. That leads us to
93 We can specify input data for analysis/plotting in 3 different
96 1. by providing a reference to an org table with the intable:
97 option. You can optionally specify the file that the table is in
98 with the infile: option;
100 2. by pointing it to a csv file, locally or via http:, using
101 infile:/path/to/file.csv or infile:http://somewhere/file.csv
103 3. by doing neither, in which case it looks for a table immediately
104 above the #+R(R) line(s).
106 Case (3) is what happened above -- the input data came from a table
107 immediately above the #+R line. The default behaviour is to replace
108 any such table with the output; this allows us to tweak the option
109 line and update the analysis. However, normally we'll want to separate
110 the data from the analysis output. So let's keep the data as a named
111 table in the org file, and refer to it by name:
122 [arbitrary other content of org buffer]
124 #+R: intable:data-set-1 action:tabulate
139 Note that this time we did a different analysis: I removed the
140 columns:2 option, so that tabulate was passed the whole table. As a
141 result the output contains counts of joint occurrences of values in
142 the two columns: out of the 4 possibilities, the only one we didn't
143 observe was "B in column 1 and A in column 2". We could have achieved
144 the same result with columns:(1 2). (But don't try to tabulate more
145 than 2 columns: org does not do multi-dimensional tables).
148 ** Available off-the-shelf plotting commands
149 At the risk of this starting to sound like a bad and boring
150 undergraduate statistics textbook, the sort of plots that are
151 appropriate depend on the sort of data. Let's divide it up as
153 - discrete-valued data
154 [e.g. data-set-1 above, or the list of org variables customised by users]
155 - continuous-valued data
156 [e.g. the wing lengths of all Eagle Owls in Europe]
158 [e.g. a data set in which each point is a time,
159 together with the size of the org source code base at that time]
161 The available off-the-shelf actions are listed [[*Table of available actions][here]].
163 ** Continuous data example:
165 :ID: 2ce0fc04-b308-4b8d-8acc-805a9e5fed7d
167 We're going to need some data. So let's prove that org can also
168 speak statistics and use org-R to simulate the data. This
169 requires some raw R code, so skip this bit if you're not
172 The following #+RR line simulates 10 values from a Normal
173 distribution with mean -3, and 10 values from a Normal
174 distribution with mean 3, and lumps them together. The point is that
175 the numbers we get should be concentrated around two different
176 values, and we should be able to see that in a histogram and/or
181 #+RR: x <- c(rnorm(10, mean=-3, sd=1), rnorm(10, mean=3, sd=1))
182 #+R: title:"continuous-data" output-to-buffer:t
186 Here's what I got. Note that the title: option set the name of the
187 table with "#+TBLNAME"; we'll use that to refer to these data.
191 #+TBLNAME:continuous-data
193 |-------------------|
194 | -2.48627002467785 |
196 | -3.43471960580471 |
197 | -5.21985294534255 |
198 | -3.84201126431028 |
199 | -1.72912705369668 |
200 | -2.86703950990613 |
201 | -2.82292622464752 |
202 | -4.43246430621368 |
203 | -1.03188727658288 |
204 | 0.882823532068805 |
216 Now to plot the data. Let's have some colour as well, and this time
217 the title: option will be used to put a title on the plot (and also to
218 name the file link to the graphical output).
223 [[file:tmp.png][histogram example]]
224 #+R: action:hist columns:1 colour:hotpink
225 #+R: intable:continuous-data outfile:"png" title:"histogram example"
228 [[file:../../images/org-R/histogram-example.png]]
230 [Note that you can use multiple #+R lines rather than cramming all
231 the options on to one line.]
233 An alternative would be to produce a density plot. We don't have
234 enough data points to justify that here, but we'll do it anyway just
235 to show the sort of plots that are produced. This time we'll specify
236 the output file for the png image using the output: option. (For the
237 histogram we used output:"png". That's a special case; it doesn't
238 create a file called "png" but instead uses org-attach to store the
239 output in the org-attach dir for this entry. Same thing for the other
240 available output image formats: "jpg", "jpeg", "pdf", "ps", "bmp",
245 [[file:density.png][density plot example]]
246 #+R: action:density columns:"values" colour:chartreuse4 args:(:lwd 4)
247 #+R: intable:continuous-data outfile:"density.png" title:"density plot example"
250 [[file:../../images/org-R/density.png]]
252 There were a couple of new features there. Firstly, I referred to
253 column 1 using its column label, rather than with the
254 integer 1. Secondly, note the use of the args: option. It takes the
255 form of a lisp property list ("p-list"), specifying extra arguments to
256 pass to the R function (in this case density()). Here we used it to
257 set the line thickness (lwd=4).
259 ** Discrete data example: the configuration variables survey
261 The raw data, as collected by Manish, are in a table called
262 org-variables-table, in a file called variable-popcon.org. We use the
263 file: option to specify the org file containing the data, and the
264 table: option to specify the name of the table within that file. [An
265 alternative be to give the entry containing the table a unique id with
266 org-id-get-create, refer to it with table:<uid>, and rely on the
267 org-id mechanism to find it.].
269 Now we tabulate the data. (We're not currently taking the sensible
270 step that Manish did of checking whether the variables were given
271 values different from their default).
273 Rather than cluttering up this org file with all the count data,
274 we'll store them in a separate org file:
278 #+R: action:tabulate columns:2 sort:t
279 #+R: infile:"variable-popcon.org" intable:"org-variables-table"
280 #+R: outfile:"org-variables-counts.org" title:"org-variables-counts"
283 [[file:org-variables-counts.org]]
285 We can see the top few rows of the table by using action:head
289 | rownames(x) | value | count |
290 |-------------+-----------------------------+-------|
291 | 1 | org-agenda-files | 22 |
292 | 2 | org-agenda-start-on-weekday | 22 |
293 | 3 | org-log-done | 22 |
294 | 4 | org-todo-keywords | 22 |
295 | 5 | org-agenda-include-diary | 19 |
296 | 6 | org-hide-leading-stars | 19 |
298 #+R: infile:"org-variables-counts.org" intable:"org-variables-counts" output-to-buffer:t
302 Here's a barplot of the counts. It makes it clear that over half the
303 org variables are customised by only one or two users.
307 [[file:org-variables-barplot.png][org-variables barplot]]
308 #+R: action:barplot rownames:t columns:1 width:800 col:darkblue
309 #+R: args:(:names.arg "NULL")
310 #+R: infile:"org-variables-counts.org" intable:"org-variables-counts"
311 #+R: outfile:"org-variables-barplot.png" title:"org-variables barplot"
314 [[file:../../images/org-R/org-variables-barplot.png]]
316 *** Something more complicated: clustering org variables, and org users
318 OK, let's make a bit more use of R's capabilities. We can use the
319 org-variables data set to define distances between pairs of org
320 users (how similar their customisations are), and distances
321 between pairs of org variables (the extent to which people who
322 customise one of them customise the other). Then we can use those
323 distance matrices to cluster org users, and org variables.
325 First, let's create a table that's restricted to variables that
326 were customised by more than four users. This isn't necessary,
327 but there are a lot of org-variables! This is going to require a
328 bit of R code to count the variables and then subset the raw data
333 [[file:variable-popcon-restricted.org][org-variables-table]]
334 #+R: infile:"variable-popcon.org" intable:"org-variables-table"
335 #+R: outfile:"variable-popcon-restricted.org" title:"org-variables-table"
336 #+RR: tab <- table(x[,2])
337 #+RR: x <- subset(x, Variable %in% names(tab[tab > 4]))
340 [[file:variable-popcon-restricted.org][org-variables-table]]
342 Now let's make a table with a row for each variable, and a column for
343 each org user, and fill it with 1s and 0s according to whether user j
344 customised variable i. We can do that without writing any R code:
348 [[file:org-variables-incidence.org][incidence-matrix]]
349 #+R: action:tabulate columns:(1 2) rownames:t
350 #+R: infile:"variable-popcon-restricted.org" intable:"org-variables-table"
351 #+R: outfile:"org-variables-incidence.org" title:"incidence-matrix"
354 [[file:org-variables-incidence.org][incidence-matrix]]
356 First we'll cluster org users. We use the R function dist to compute a
357 distance matrix from the incidence matrix, then hclust to run a
358 hierarchical clustering algorithm, and then plot to plot the results
363 [[file:org-users-tree.png][org-users-tree.png]]
364 #+RR: par(bg="gray15", fg="turquoise2")
365 #+RR: plot(hclust(dist(x, method="binary")), ann=FALSE)
366 #+R: infile:"org-variables-incidence.org" intable:"incidence-matrix" rownames:t
367 #+R: outfile:"org-users-tree.png" title:"org-users-tree.png"
370 [[file:../../images/org-R/org-users-tree.png]]
372 And to cluster org variables, we use the transpose of that incidence matrix:
376 [[file:org-variables-tree.png][org-variables-tree.png]]
377 #+RR: par(bg="gray15", fg="turquoise2")
378 #+RR: plot(hclust(dist(t(x), method="binary")), ann=FALSE)
379 #+R: infile:"org-variables-incidence.org" intable:"incidence-matrix" rownames:t
380 #+R: outfile:"org-variables-tree.png" title:"org-variables-tree.png" width:1000
383 [[file:../../images/org-R/org-variables-tree.png]]
386 Please note that my main aim here was to give some examples of using
387 org-R, rather than to show how the org variables data should be mined
388 for useful information! The org-variables dendrogram does seem to have
389 made some sensible clusterings (e.g. the clusters of agenda-related
390 commands), but I'm going to leave it to others to decide whether this
391 exercise really served to do more than illustrate org-R. Does anyone
392 recognise any usage affinities between the clustered org users?
394 ** Indexed data example
396 :ID: 45f39291-3abc-4d5b-96c9-3a32f77877a5
398 Let's plot the same data as Eric Schulte used in the [[../org-plot.org][org-plot tutorial]] on worg.
402 [[file:/usr/local/src/org-etc/Worg/org-tutorials/org-R/data/45/f39291-3abc-4d5b-96c9-3a32f77877a5/org-R-output-8119M2O.png][An example from the org-plot tutorial, plotted using org-R]]
403 #+R: action:lines columns:((1)(2 3))
404 #+R: infile:"../org-plot.org"
405 #+R: intable:"org-plot-example-1" outfile:"png"
406 #+R: title:"An example from the org-plot tutorial, plotted using org-R"
409 [[file:../../images/org-R/org-plot-example-1.png]]
411 * Table of available options
412 In addition to the action:<some-action> option (described [[*Table of available actions][here]], the
413 following options are available:
414 |-----------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------|
415 | *Input options* | |
416 |-----------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------|
417 | infile:/path/to/file.csv | input data comes from file.csv |
418 | infile:http://www.somewhere/file.csv | input data comes from file.csv somewhere on the web |
419 | infile:/path/to/file.org | input data comes from file.org; must also specify table with intable:<name-or-id> |
420 | intable:table-name | input data is in table named with #+TBLNAME:table-name (in same buffer unless infile:/path/to/file.org is specified) |
421 | intable:table-id | input data is first table under entry with table-id as unique ID. Doesn't make sense with infile:/path/to/file.org |
422 | rownames:t | does first column contain row names? (default: nil). If t other column indices are as if first column not present -- this may change) |
423 | colnames:nil | does first row contain column names? (default: t) |
424 | columns:2 columns:(2) | operate only on column 2 |
425 | columns:"wing length" columns:("wing length") | operate only on column named "wing length" |
426 | columns:((1)(2 3)) | (when plotting) plot columns 2 and 3 on y-axis against column 1 on x-axis |
427 | columns:(("age")("wing length" "fierceness")) | (when plotting) plot columns named "wing length" and "fierceness" on y-axis against "age" on x-axis |
428 |-----------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------|
429 | *Action options* | |
430 |-----------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------|
431 | action:some-action | off-the-shelf plotting action or computation (see [[*Table of available actions][separate list]]), or any R function that makes sense (e.g. head, summary) |
432 | lines:t | (when plotting) join points with lines (similar to action:lines) |
433 | args:(:xlab "\"the x axis title\"" :lwd 4) | provide extra arguments as a p-list (note the need to quote strings if they are to appear as strings in R) |
434 |-----------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------|
435 | *Output options* | |
436 |-----------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------|
437 | outfile:/path/to/image.png | save image to file and insert link into org buffer (also: .pdf, .ps, .jpg, .jpeg, .bmp, .tiff) |
438 | outfile:png | save image to file in org-attach directory and insert link |
439 | outfile:/path/to/file.csv | would make sense but not implemented yet |
440 | height:1000 | set height of graphical output in (pixels for png, jpeg, bmp, tiff; default 480) / (inches for pdf, ps; default 7) |
441 | width:1000 | set width of graphical output in pixels (default 480 for png) |
442 | title:"title of table/plot" | title to be used in plot, and as #+TBLNAME of table output, and as name of link to output |
443 | colour:hotpink col:hotpink color:hotpink | main colour for plot (i.e. `col' argument in R, enter colors() at R prompt for list of available colours.) |
444 | sort:t | with action:tabulate, sort in decreasing count order (default is alphabetical on names) |
445 | output-to-buffer:t | force numerical output to org buffer (shouldn't be necessary) |
446 | inline:t | don't name links to output (so that graphics are inline when exported to HTML) |
447 |-----------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------|
449 |-----------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------|
450 | showcode:t | Display a buffer containing the R code that was generated to do what was requested. |
452 * Table of available actions
454 To specify an action from the following list, use e.g. action:hist on
457 | *Actions that generate numerical output* | |
458 |------------------------------------------+---------------------------------------------------------------------------------------------------------|
459 | tabulate | count occurrences of distinct input values. Input data should be discrete. This is function table in R. |
460 | summary | summarise data in columns (minimum, 1st quartile, median, mean, 3rd quartile, max) |
461 | head | show first 6 rows of a larger table |
462 | transpose | transpose a table |
464 | *Actions that generate graphical output* | |
465 |------------------------------------------+---------------------------------------------------------------------------------------------------------|
467 | *Discrete data* | |
468 | barplot | produces 'side-by-side' bar plots if multiple columns selected |
471 | plot | if only 1 column selected, index is automatic: 1,2,... |
472 | lines | same as plot |
473 | points | same as plot but don't join points with lines |
475 | *Continuous data* | |
477 | density | like a smoothed histogram (i.e. a curve) |
479 | *Grid of values* | |
480 | image | a grid image, with cells coloured according to their numerical values |
483 Apart from tabulate, the action: names are the same as the names of
484 the R functions which implement them. `tabulate' is really called
487 Note that, in addition to the actions listed below, you can also use
488 action:R-function, where "R-function" is the name of any existing R
489 function. The function must be able to take a data frame as it's first
490 argument, and must not *require* any further arguments (i.e. any
491 further arguyments must have suitable default values). Any numerical
492 output will be sent to the org buffer (use output-to-buffer:t to force
493 this, although if that is necessary then that is a bug).
496 * More detailed description of org-R
497 My aim with org-R is to provide a fairly general facility for using
498 R with Org. The #+R lines and #+RR lines together specify an R
499 function, which may take numerical input, and may generate
500 graphical output, or numerical output, or both.
502 If any input data have been specified, then the R function receives
503 those data as its first argument. The input data may come from an
504 Org table, or from a csv spreadsheet file. In either case they are
505 tabular (1- or 2-dimensional). The input data are passed to the
506 function as an R data frame (a table-like structure in which
507 different columns may contain different types of data -- numeric,
508 character, etc). Inside the R function, that data frame is called
509 'x'. 'x' is also the return value of the R function. Therefore the
510 numerical output of org-R is determined by the modifications to the
511 variable x that are made inside the function (any graphical output
514 It's worth noting that one mode of using org-R would be to write your
515 own code in a separate file, and use the source() function on a #+RR
516 line to evaluate the code in that file.
518 Numerical output of the function should also be tabular, and may be
519 received by the Org buffer as an Org table, or sent to file in Org
520 table or csv format. R deals transparently with multi-dimensional
521 arrays, but Org table and csv format do not.
523 Unless an output file has been specified, graphical output will be
526 The mapping from the #+R and #+RR lines to the R function may
527 benefit from further thought; currently what happens is that code
528 corresponding to the #+R line is generated, and then any explicit
529 user code is appended to this. Thus the #+RR lines have the 'last
530 word' on the output. Since multiple, intermixed, #+R and #+RR
531 lines can be given, it might make sense instead to follow the order
532 of those lines when constructing the code.
535 * Getting help with R
536 - Bring up an R prompt with R at a shell prompt, or M-x R in emacs (if you have installed ESS)
537 - Enter ?function.name for help on function `function.name'
538 - Enter RSiteSearch("words") for online help matching "words"
539 - Enter ?par to see the full list of graphical parameters
540 - Follow the Documentation link on the left hand side of the R
541 website for "An Introduction to R", and other more technical manuals.
543 Seeing as this has made use of R, I'll briefly say my bit on it for
544 those who are unfamiliar.
545 1. It's good for simple numerical work, as well as having
546 implementations of a a very large range of more sophisticated
547 mathematical and statistical procedures.
548 2. It's good for producing graphics quickly, and for fine tuning
549 every last detail of the graphics for publication.
550 3. It's a syntactically reasonable, user-friendly, interpreted
551 programming language, that is often used interactively (it comes
552 with its own shell/command-line environment, and runs within
554 4. It's a good language for a functional style of programming (in
555 fact I'd say that's how it should be used), which might well
556 appeal to elisp programmers. For example, you want to construct
557 an arbitrarily nested data structure, then pass some function
558 over the tips, returning a data structure of the same shape as
559 the input? No problem ([[http://stat.ethz.ch/R-manual/R-patched/library/base/html/rapply.html][rapply]]).
560 5. There's a *lot* of add-on packages for it (CRAN link on left hand
561 side of [[http://www.r-project.org/][website]].).
562 6. How many programming languages will get [[http://www.nytimes.com/2009/01/07/technology/business-computing/07program.html][their own article]] in the
563 New York Times this year?