Create org-tools/ and add info about orgnode.py
[Worg.git] / FIXME / ob-doc-R-extended.org
blob84f2e29e92a1923149455dfffb4db2d5bcf18bca
1 #+OPTIONS:    H:3 num:nil toc:2 \n:nil @:t ::t |:t ^:{} -:t f:t *:t TeX:t LaTeX:t skip:t 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) noexport(n)
5 #+TITLE:    Org-mode and R: An Introduction
6 #+AUTHOR:    Erik Iverson
7 #+EMAIL:     eriki at ccbr dot umn dot edu
8 #+LANGUAGE:   en
9 #+STYLE:      <style type="text/css">#outline-container-introduction{ clear:both; }</style>
10 #+BABEL: :exports both
12 This is an introduction to using R ([[http://www.R-project.org]]) source
13 code within Emacs org-mode ([[http://orgmode.org]]). Org-mode files use
14 headlines to organize information. Each top-level headline in this
15 document starts with a single '*', like the "Introduction" headline
16 below. While this is not an introduction to using org-mode, you will
17 need to know one command to proceed: use the TAB key on a headline to
18 open it. TAB will cycle through the possible visibility states of the
19 information under the headline, and eventually TAB will collapse the
20 headline back to how you see it now. One last command to note: C-c C-o
21 opens links like those above in your web browser. I have tried to link
22 to the appropriate documentation for each feature I describe.
24 Since you are following along in org-mode, instead of reading this in
25 an exported format like HTML or PDF, you will need org-mode 7.01 or
26 greater to go interact with this tutorial. See [[http://orgmode.org/index.html#sec-3][here]] for instructions
27 on how to download the latest version of org-mode. To see what version
28 of org-mode you have installed, type M-x org-version, and hit
29 <ENTER>. The result will be in the minibuffer. If the version is
30 anything less than 7.01, you'll need to update to run the examples.
31 If you have an older version of org-mode, and just want to read about
32 the possibilities, you can continue on.
34 * Introduction
36 #+begin_html
37   <div id="subtitle" style="float: center; text-align: center;">
38   <p>
39   Org-mode support for
40   <a href="http://www.r-project.org/">R</a>
41   </p>
42   <p>
43   <a href="http://www.r-project.org/">
44   <img src="http://www.r-project.org/Rlogo.jpg"/>
45   </a>
46   </p>
47   </div>
48 #+end_html
50 Emacs org-mode 7.01 has an exciting new feature that lets you submit
51 source code blocks within an org-mode document for evaluation. This
52 lets you do things like insert the results of R code into an Emacs
53 buffer, insert graphical and tabular material into a buffer, or pass
54 the results of R code to other programming languages such as Python. R
55 code and results can be included in your exported org-mode documents,
56 opening up several interesting possibilities for automatically
57 generating comprehensive documentation and advanced reports. You can
58 also extract the source code portions of an org-mode document for
59 further processing, through a process called tangling. This tutorial
60 will get you started using these org-mode features together with the R
61 programming language.
63 If you are unfamiliar with org-mode itself, you can learn a lot more
64 from the project's [[orgmode.org][website]]. There are many good tutorials available on
65 org-mode already. The [[http://orgmode.org/guide/index.html][compact guide]] is a great place to start. This
66 current document focuses on source code support. Note that while the
67 features being demonstrated in this document were being developed, the
68 project was known as org-babel. Thus, many of the variables and
69 function names reference 'org-babel' in their names. Org-babel is now
70 distributed with org-mode, so many of the previous configuration
71 hurdles are now avoided. Keep this in mind as you read old mailing
72 list posts and documentation. The authors of org-babel are Eric
73 Schulte and Dan Davison. They have worked very hard creating this
74 amazing system!
76 Although you may be viewing this tutorial in an exported format like
77 HTML or PDF, I wrote this tutorial in org-mode. You will benefit most
78 from it by following along in org-mode. Only then can you
79 interactively evaluate the examples to see org-mode in action. For
80 this reason, I suggest you download the [[http://repo.or.cz/w/Worg.git/blob_plain/HEAD:/org-contrib/babel/languages/ob-doc-R-extended.org][actual org mode file]] that this
81 document is based on, visit the file in Emacs, and follow along there.
83 For those following along in an exported version, such as HTML, 
84 in the actual org-mode file, source code blocks look like this:
86 #+begin_example
87 #+begin_src R 
88   # some R code 
89   square <- function(x) 
90   {
91     x * x
92   }
93     
94   square(1:10)
95 #+end_src 
96 #+end_example
98 However, when they are /exported/ into documents like this they will
99 look like:
101 #+begin_src R :exports code
102   # some R code 
103   square <- function(x) 
104   {
105     x * x
106   }
107     
108   square(1:10)
109 #+end_src 
111 It's something to be aware of when following along from an exported
112 version such as HTML, since I will be referencing source code block
113 arguments that you will not be able to see.  That is another very good
114 reason to follow along with the [[http://repo.or.cz/w/Worg.git/blob_plain/HEAD:/org-contrib/babel/languages/ob-doc-R-extended.org][raw org mode file]]. 
116 This tutorial was written in GNU Emacs 23.2 on Ubuntu 10.04, org-mode
117 version 7.01trans, pulled directly from the org-mode git repository.
119 Please send any questions or corrections to eriki at ccbr dot umn dot edu. 
121 ** System Prerequisites for this tutorial 
123 First, we need to make sure our environment is setup correctly for the
124 examples to run.  This requires a bit more work under Windows than
125 others, see below.
127 Here is a list of software we need to run the examples:
128 1) org-mode 7.01 or greater, see [[http://orgmode.org]]
129 2) a working R installation, see [[http://www.R-project.org]]
130 3) The R examples use the ggplot2 and Hmisc packages from CRAN. Simply install from the
131    R command line by issuing the command, 
132    > install.packages(c("ggplot2", "Hmisc"))
133    R must be in your PATH environment variable.  For Windows users, you will probably
134    have to add this yourself. 
136 For LaTeX support, 
137 4) a working LaTeX installation, see [[http://latex-project.org]]. Windows users
138    can use [[http://miktex.org/][MikTeX]].  
139 5) dvipng program (comes with MikTeX or texlive-full Ubuntu package)
141 6) Some extra LaTeX packages (comes with texlive-full Ubuntu package): 
143    I found that on my Ubuntu 10.04 installation, I had to install the
144    texlive-latex-extra and texlive-fonts-recommended packages to get
145    the LaTeX documents that org-mode produces to compile. You can get
146    both of these (plus dvipng) through the Ubuntu package
147    texlive-full, so simply installing the `texlive-full` package may
148    be the easiest option if you happen to be on Ubuntu.
150    For Windows users who have installed MikTeX, I had to use the
151    MikTeX package manager to install the following packages for LaTeX
152    support to work: soul, marvosysm, wasysym, wasy, zhmetrics. Install
153    these and you should be good to go.
155 For inline image support,
156 7) libpng, GNU/Linux users probably have this.  I found under Windows
157    that I had to download
158    http://downloads.sourceforge.net/gnuwin32/libpng-1.2.37-setup.exe
159    and after running the installation program, *manually* copy the
160    libpng12.dll and zlib1.dll files into my emacs-23.x\bin directory,
161    and then restart emacs for inline image support to work. One easy
162    way to test if png support is working is to simply open a png file
163    within Emacs from dired.
164   
165 * Setting up org-mode for source code evaluation 
167 Setting up org-mode to run source code is very simple. Since you are
168 reading the R tutorial, I will assume you want to specifically run R
169 source code blocks within org-mode. Since we use LaTeX later on in 
170 the tutorial, we'll also take the opportunity to set up org-mode
171 to evaluate LaTeX blocks. 
173 The absolute, bare minimum setup you need to perform is to run the
174 following Emacs lisp code. For a preview of what we're going to learn
175 with in this tutorial, simply hit C-c C-c anywhere in the following code
176 block! You will be asked in the minibuffer to confirm that you want
177 to evaluate the source code contained in the block. Confirm this, and
178 you'll be set up for the rest of the tutorial. You can also add the
179 lines between the #+begin\_src and #+end\_src lines to your Emacs
180 initialization file, so that they are always run when starting Emacs.
182 So go ahead, hit C-c C-c with point in the following code block. 
184 #+begin_src emacs-lisp :results silent
185   (org-babel-do-load-languages
186    'org-babel-load-languages
187    '((R . t)
188      (latex . t)))
189 #+end_src
191 If you received any type of error message, please make sure that you
192 have the proper version of org-mode installed by typing M-x
193 org-version <Enter>. You should have at least 7.01. If you still are
194 running org-mode version 6.xx or before, please visit the project web
195 site for instructions on downloading the latest version.
197 If you didn't get any errors, org-mode is now setup to run the R
198 examples that follow.
200 Note to Windows users. Make sure the directory containing the R
201 executable is added to your PATH variable for you to run these
202 examples.
204 ** Prompting for confirmation before evaluating code 
205 There is one more variable I set in my Emacs initialization file
206 relating to evaluating source code in org-mode. By default, org-mode
207 will ask you to confirm each and every time you evaluate a source code
208 block. If you ran the above source code block with C-c C-c, you will
209 have noticed that behavior. I turn this feature off with the
210 following line. If you choose, simply hit C-c C-c to evaluate it for
211 this session, or put it in your Emacs initialization file. Then, you
212 won't be asked before org-mode evaluates source code blocks. You may
213 view this as a security risk. Always look over the code you're going
214 to evaluate before submitting it. 
216 #+begin_src emacs-lisp :results silent :exports code
217   (setq org-confirm-babel-evaluate nil)
218 #+end_src
220 ** Other supported languages
222 Besides R, which we just set up with the above source code block, see
223 [[http://orgmode.org/manual/Languages.html#Languages][here]] for a list of languages that org-mode currently supports. You can
224 then add more languages to your personal setup if you desire, by
225 modifying the variable we defined above to include more languages.
227 * Org-mode source code blocks 
228 ** Exporting pretty-printed source code blocks
230 Before I show you how to evaluate code in org-mode, let's start off
231 with looking at a what a typical org-mode code block looks like. We
232 just saw a couple examples above of Emacs lisp source code blocks. In
233 what follows, we will be working with very simple R functions to show
234 off the capabilities of org-mode.
236 The following is a simple R code block in org-mode. You can edit the
237 code in its own buffer by typing C-c ' (that's a single quote), or
238 just by editing the code within the org-mode buffer. The nice thing
239 about opening the code in its own buffer with C-c ', is that the
240 buffer is then in ESS mode. All the ESS key bindings, interaction
241 with the inferior R process, and syntax highlighting work as expected.
243 So here is an example of a source code block. The defining feature is
244 the #+begin\_src and #+end\_src lines, with the language definition,
245 "R", on the first line. 
247 Try opening this code block by putting point anywhere inside of it,
248 and hitting C-c ' (that's a single quote). This will open a new
249 buffer, with the contents of the source code block. You can then edit
250 this buffer just like any other R file, as it is in R-mode from
251 ESS. When finished editing, hit C-c ' again, and you'll see any
252 changes you made reflected in this org-mode buffer. You can control
253 how this new buffer is displayed by setting the org-src-window-setup
254 variable in Emacs.
256 #+begin_src R :exports code
257   square <- function(x) 
258   {
259     x * x
260   }
261     
262   square(1:10)
263 #+end_src 
265 So now we have this code block defined. Why would we want to do
266 something like that with org-mode? Mostly so that when we export an
267 org-mode document to a more human-readable format, org-mode recognizes
268 those lines as syntax, and highlights them appropriately in the HTML
269 or LaTeX output. The lines will be syntax highlighted just like they
270 would be in an R code buffer in Emacs.
272 Try this for yourself. With point anywhere in this subtree, for
273 example, put it here [ ], hit C-c C-e 1 b (that's the number 'one').
274 This subtree should be exported to an HTML file and displayed in your
275 web browser. Notice how the source code is syntax highlighted. 
277 Note: for syntax highlighting in exported HTML to work, htmlize.el
278 must be in your load-path. The easiest way to make that happen if you
279 haven't already is to run the following Emacs lisp code, *after*
280 changing the "/path/to" portion to reflect your local setup. I have
281 the following in my Emacs init file. 
283 #+begin_src emacs-lisp :results silent :exports code
284  (add-to-list 'load-path "/path/to/org-mode/contrib/lisp")
285 #+end_src
287 ** Evaluating the code block using org-mode
289 As I mentioned, defining the above code block would be useful if
290 we wanted to export the org-mode document and have the R code in the
291 resulting, say, HTML file, syntax highlighted. The feature that
292 org-mode now adds in version 7.01 is letting us actually submit the
293 code block to R to compute results for either display or further
294 computation.
296 It is worth pointing out here that org-mode works with many
297 languages, and they can all be intertwined in a single org-mode
298 document. So you might get results from submitting an R function, and
299 then pass those results to a Python or shell script through an
300 org-table. Org-mode then becomes a meta-programming tool. We only
301 concentrate on R code here, however.
303 We did see above in the setup section that we have Emacs lisp code in
304 this same org-mode file. To be clear, you can mix many languages in
305 the same file, which can be very useful when writing documentation,
306 for instance.
308 Next, let's actually submit some R code.
310 *** Obtaining the return value of an R code block
312 We will now see how to submit a code block. Just as in the
313 Introduction with Emacs lisp code, simply hit C-c C-c anywhere in the
314 code block to submit it to R. If you didn't set the confirmation
315 variable to nil as I described above, you'll have to confirm that you
316 want to evaluate the following R code. So go ahead, evaluate the
317 following R code block with C-c C-c and see what happens. 
319 #+begin_src R
320   square <- function(x) {
321     x * x
322   }
323   
324   square(1:10)
325 #+end_src 
327 If you've submitted the code block using C-c C-c, and everything went
328 well, you should have noticed that your buffer was modified. Org-mode
329 has inserted a results section underneath the code block, and above
330 this text. These results are from running the R code block, and
331 recording the last value. This is just like how R returns the last
332 value of a function as its return value. Notice how the results have
333 been inserted as an org-table. This can be very useful. However,
334 what if we wanted to see the standard R output? You will see how to do
335 that in the next section.
337 You can also try changing the source code block, and re-running it.
338 For example, try changing the call to the square function to 1:12,
339 then hit C-c C-c again. The results have updated to the new value!
341 *** Obtaining all code block output 
343 We just saw how the last value after evaluating our code is put into
344 an org-mode table by default. That is potentially very useful, but
345 what if we just want to see the R output as it would appear printed in
346 the R console? Well, just as R function have arguments, org-mode
347 source blocks have arguments. One of the arguments controls how the
348 output is displayed, the :results argument. It is set to 'value' by
349 default, but we can change it to 'output' to see the usual R
350 output. Notice the syntax for setting source code block arguments
351 below.
353 #+begin_src R :results output
354   square <- function(x) {
355     x * x
356   }
358   square(1:10)
359 #+end_src 
362 Now we see the typical R notation for printing a vector. Note in the
363 following example that setting `:results output` captures *all*
364 function output, not just the return value. We capture things printed
365 to the screen with the `cat` function for example, or the printing of
366 the variable `x`.
368 #+begin_src R :results output
369   x <- 1:10
370   x
371   square <- function(x) {
372     cat("This is the square function.\n")
373     x * x
374   }
375   
376   square(1:10)
377 #+end_src 
379 Try changing the :results argument to `value` (which is the same as
380 omitting it completely), and re-run the above code block. You should
381 see the same org-table output as we saw above.
382 *** More information on org-mode source block headers
384 See [[http://orgmode.org/manual/Header-arguments.html#Header-arguments]]
385 for more information on source code block header arguments, including
386 the various ways they can be set in an org-mode document: per block,
387 per file, or system-wide.
389 *** Inline code evaluation 
390 Much like the Sweave \Sexpr command, we can evaluate small blocks of
391 inline code using the
393 #+begin_example
394 SRC_R[optional header arguments]{R source code} 
395 #+end_example
397 syntax.  So, in org-mode I will type
399 #+begin_example
400 SRC_R[:exports results]{round(pi, 2)}
401 #+end_example 
403 and you will see src_R[:exports results]{round(pi, 2)} in the exported
404 output.  You'll see examples of how to use the :exports code block
405 header in a few sections. 
406 * Passing data between code blocks
408 One of the biggest limitations to using code blocks like above is that
409 a new R session is started up `behind the scenes` when we evaluate
410 each code block. So, if we define a function in one code block, and
411 want to use it another code block later on, we are out of luck. This
412 limitation can be overcome by using R session-based evaluation, which
413 sends the R code to a running ESS process.
415 ** R session-based evaluation 
417 Often in R, we will define functions or objects in one code block
418 and want to use these objects in subsequent code blocks. However,
419 each time we submit a code block using C-c C-c, org-mode is firing up
420 an R session, submitting the code, obtaining the return values, and
421 closing down R. So, by default, our R objects aren't persistent!
422 That's an important point. Fortunately, there is an easy way to tell
423 org-mode to submit our code blocks to a running R process in Emacs,
424 just like we do with R files in ESS.
426 You simply use the :session argument to the org-mode source block.   
428 #+begin_src R :session :results output
429   square <- function(x) {
430     x * x
431   }
432   x <- 1:10 
433 #+end_src 
435 So, the above code block defines our function (square) and object (x).
436 Now we want to apply call our square function with the x
437 object. Without :session, we could not do this.
439 #+begin_src R
440   square(x)
441 #+end_src
443 Running the above code block will result in an error, since a new R
444 session was started, and our objects were not available. Now try the
445 same code block, but with the :session argument, as below.
447 #+begin_src R :session :results output
448   square(x)
449 #+end_src
451 The results we expect are now inserted, since we submitted this code
452 block to the same R session where the square function was defined.
454 ** Code blocks using different languages
456 Even though this tutorial covers the R language, one of org-mode's
457 main strengths is its ability to act as a meta programming language,
458 using results from a program written in one language as input to a
459 program in another language.
462 [[http://orgmode.org/worg/org-contrib/babel/intro.php#meta-programming-language]]
463 for an example of this. To keep things as focused on R as possible, I
464 chose not to include an example like the one found in the link in this
465 tutorial.
467 * Inserting R graphical output 
469 Here is a really cool feature of evaluating source code in
470 org-mode. We can insert images generated by R code blocks inline in
471 our Emacs buffer! To enable this functionality, we need to evaluate a
472 bit of Emacs lisp code. If this feature is something you want every
473 time you use org-mode, consider placing the code in your Emacs
474 initialization file. Either way, evaluate it with C-c C-c.
476 #+begin_src emacs-lisp :results silent :exports code
477   (add-hook 'org-babel-after-execute-hook 'org-display-inline-images)   
478   (add-hook 'org-mode-hook 'org-display-inline-images)   
479 #+end_src
481 The following R code generates some graphical output. There are
482 several things to notice.
484 1) :results output is specified. This is because the figure is
485    generated using the ggplot2 package in R, which is based on
486    something called `grid` graphics. Grid graphics need to be
487    explicitly printed when called within a function for their output
488    to be displayed. See, for example, [[http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-do-lattice_002ftrellis-graphics-not-work_003f][R FAQ 7.22]]. When :results value
489    (the default) is active, Org-mode is generating an R function
490    wrapper. The upshot is: when generating grid-based graphical output
491    within org-mode, you need to either use :results output, wrap the
492    graphical function in a print call, or use the :session
493    argument. See this mailing list [[http://www.mail-archive.com/emacs-orgmode@gnu.org/msg25944.html][post]] for more explanation if you'd
494    like.
496 2) We use a new source code block argument, :file. This argument will
497    capture graphical output from the source block and generate a file
498    with the given name. Then, the results section becomes an org-mode
499    link to the newly created file. In the example below, the file
500    generated is called diamonds.png.
502    Finally, If you have defined the Emacs lisp code for inline-image
503    support above, an overlay of the file will be inserted inline in
504    the actual org-mode document! Run the following source code block
505    to see how it works.
507 #+begin_src R :results output :file diamonds.png
508   library(ggplot2)
509   data(diamonds)
510   dsmall <-diamonds[sample(nrow(diamonds), 100), ] 
511   qplot(carat, price, data = dsmall)
512 #+end_src
513   
514 This opens up many opportunities for doing interesting things with R
515 within your org-mode documents!
517 * Inserting LaTeX output
519 We have just seen how to include graphical output in our org-mode
520 buffer. We can also do something similar with LaTeX output generated
521 by R. Of course, this requires at least a working LaTeX
522 installation. You will also need to install the dvipng program (dvipng
523 package in Ubuntu, for instance). See the System Requirements section
524 for other prerequisites.
526 ** A simple example 
528 Let's work on a very simple example, displaying a LaTeX description
529 in our org-mode buffer, using the official LaTeX logo. We will use R
530 to generate the code that will display the official logo. There's
531 obviously no reason to do this except for demonstration purposes.
533 First we must define an R source block that generates some LaTeX code
534 that displays the logo. That's fairly straightforward. Notice we have
535 given the source code block a name, so that we can call it later. We
536 use the #+srcname syntax to do this. Note that you *don't* have to
537 run the following code block, it will be run automatically by the next
538 one.
540 #+srcname: R-latex
541 #+begin_src R :results silent :exports code
542   lf <- function() {
543       "\\LaTeX"
544   }
545   
546   lf()
547 #+end_src
549 Next, we define a new source block using the "latex" language, instead
550 of "R", as we have been using. If we use a :file argument with a LaTeX
551 source code block, org-mode will generate a file of the resulting dvi
552 file that LaTeX produces, and display it. This is just like
553 generating graphical output from R using a :file argument, so there is
554 nothing new there.
556 However, note we have a new argument, :noweb. What does that mean? In
557 short, it let's us use syntax like <<CodeBlock()>> to insert the
558 results of running a code block named CodeBlock into another source
559 code block. So, in our example, we're running the R-latex code block
560 defined above, and inserting the results, which need to be valid LaTeX
561 code, into our latex code block. For this example, we of course didn't
562 need to write an R function to generate such simple LaTeX output, but
563 it can be much more complicated, as our next example shows. In short,
564 our R code block is helping to write the LaTeX code block for us.
566 Noweb was not invented for org-mode, it's been around for a while, and
567 is used in Sweave, for example. See [[http://en.wikipedia.org/wiki/Noweb][its Wikipedia page]]. The :noweb
568 argument is set to 'no' be default, because the <<X>> syntax is
569 actually valid in some languages that org-mode supports.
571 Run the following code block. The "R-latex" R code block will be run,
572 generating the string \\LaTeX, which is then substituted into this
573 LaTeX code block, and then turned into the LaTeX logo by the latex
574 program. Don't worry about the complicated header arguments, those
575 will be explained in more detail in the next section. 
577 #+begin_src latex :noweb yes :file (if (and (boundp 'htmlp) htmlp) "latex-logo-html.png" "latex-logo.png") :buffer (if (and (boundp 'htmlp) htmlp) "no" t)
578 <<R-latex()>>~is a high-quality typesetting system; it includes
579 features designed for the production of technical and scientific
580 documentation. <<R-latex()>>~is the de facto standard for the
581 communication and publication of scientific
582 documents. <<R-latex()>>~is available as free software.
583 #+end_src
585 ** A more complicated example, exporting LaTeX in buffer, to HTML, and to PDF
587 Now let's try something a little more complex, using an R function
588 that generates a full LaTeX table. This particular example depends on
589 having the R package Hmisc installed. If you don't have it installed,
590 start up R and then do: > install.packages("Hmisc")
592 What follows is an R source block that generates some LaTeX code
593 representing a table.  We want to be able to insert a =png= image of
594 the table in the buffer when run with C-c C-c, using the colors of our
595 current Emacs buffer.
597 A few sections from now, I'll touch on the exporting features of
598 org-mode.  Org can generate HTML and PDF versions of documents like
599 this one. 
601 Back to our example, for HTML export, we also want to generate a
602 =png=. However, we want the background to be transparent, not whatever
603 color our Emacs buffer happened to be.
605 For LaTeX output, we don't need a =png= file at all, we would of
606 course prefer to simply insert the auto-generated LaTeX code in the
607 exported LaTeX document, and then compile to PDF.
609 The following should accomplish all three goals.  
611 We tell the R code block to output latex code using the syntax
612 /:results output latex/.  Also, only export the code.  If we export
613 both, then the LaTeX results would get exported twice when we export
614 to PDF, once from each code block.  It would actually be exported
615 twice when we export to HTML, but in that case, since the results are
616 wrapped in #+BEGIN\_LATEX/#+END\_LATEX lines, and are therefore not
617 included in the HTML export.
619 In the LaTeX code block, a file will be generated for in-buffer
620 evaluation and HTML export, but we don't want it produced for LaTeX
621 export, otherwise the image /and/ the actual table will be included in
622 the PDF.  
624 The final /buffer/ argument controls the color selection through the
625 =org-format-latex-options= variable. Essentially, if buffer is set to
626 'yes', your Emacs buffer colors will be used as arguments to the
627 =dvipng= program used to produce the image, assuming you don't change
628 that values of the elements to something other than 'default' in
629 =org-format-latex-options=. If buffer is 'no', then the html* elements
630 of that variable will be used.
632 #+srcname:Hmisc-latex
633 #+begin_src R :results output :exports code
634   set.seed(1) 
635   library(Hmisc)
636     
637   df <- data.frame(age = rnorm(100, 10),
638                    gender = sample(c("Male", "Female"), 100, replace = TRUE),
639                    study.drug = sample(c("Active", "Placebo"), 100, replace = TRUE))
641   label(df$study.drug) <- "Treatment" 
642   label(df$age) <- "Age at randomization" 
643   label(df$gender) <- "Gender" 
644     
645   latex(summary(study.drug ~ age + gender, data = df,
646                 method = "reverse", overall = TRUE, test = TRUE), 
647         long = TRUE,  file = "", round = 2, exclude1 = FALSE, npct = "both",
648         where="!htbp")
649 #+end_src
651 #+begin_src latex :noweb yes :file (if (and (boundp 'latexp) latexp) nil (if (and (boundp 'htmlp) htmlp) "hmisc-html.png" "hmisc.png")) :buffer (if (and (boundp 'htmlp) htmlp) "no" t)
652 <<Hmisc-latex()>>
653 #+end_src 
655 * Putting it all together, a notebook interface to R
657 Combining the techniques shown above: submitting code blocks,
658 capturing output for further manipulation, and inserting graphical and
659 tabular material, we essentially have a basic notebook-style
660 interface for R.
662 This is potentially useful for countless tasks such as: a laboratory
663 notebook, time series analysis of diet/exercise habits, tracking your
664 favorite baseball team over the course of a season, or any reporting
665 task you can think of. Since org-mode is a general-purpose authoring
666 tool, with very strong exporting capabilities, almost anything is
667 possible.
669 For instance, I use org-mode to generate HTML for an R blog that I
670 run. Several posters to the org-mode mailing list have mentioned
671 writing their entire graduate theses in org-mode, and even books.
673 I look at this workflow as an alternative to the excellent [[http://www.stat.uni-muenchen.de/~leisch/Sweave/][Sweave]]
674 package that cuts out the need for learning LaTeX to produce
675 high-quality documents. Org-mode is doing all the exporting for you,
676 including LaTeX if you'd like. Getting LaTeX and HTML output
677 essentially "for free" should not be underestimated!
679 On some level, all these activities assume that you are a comfortable
680 org-mode user, and that you will be writing code, conducting analyses,
681 and possibly exporting results through the familiar Emacs and org-mode
682 user interface. Through the exporting functionality, org-mode offers
683 many useful and easy-to-use options to share /results/ of your efforts
684 with others, but what about the code itself? 
686 Most people you have to share code with aren't going to want an
687 org-mode file full of source code!
689 * Tangling code 
691 With many projects, you will have to share /code/ with other
692 programmers, who are most likely not going to be programming in
693 org-mode. Therefore, sharing an org-mode file full of code is not an
694 option.
696 Or, consider development of an R package. The package building
697 process obviously operates on .R files, each full of R functions.
698 However, that's not what we have in a document like this one.
700 It is in situations like these where /tangling/ can be used. 
702 The process of tangling an org-mode document essentially extracts the
703 code contained in org-mode source code blocks, and places it in a file
704 of the appropriate type. How do we do this? We use the :tangle
705 source code block header argument to direct org-mode what to do. Then,
706 we call the tangle function on the file to extract the source code!
708 Read on to learn how to perform each of these steps. 
710 ** Instructing org-mode how to tangle with header arguments 
711 Let's take a look at a few examples. Each example contains an R
712 comment, so that you can see in the resulting .R file where it came
713 from.
715 This first example will not extract any code from the source block.
716 It is the default behavior. 
718 #+begin_src R :tangle no :exports code
719 # tangle was not specified
720 x <- 1:10
721 print(x) 
722 #+end_src
725 This will place the code in source code block in
726 org-mode-R-tutorial.R, since we don't specify a filename for the .R
727 file.
729 #+begin_src R :tangle yes :exports code
730 # tangle was specified, but no file given
731 x <- 1:10
732 print(x)
733 #+end_src
735 This will place the tangled code in Rcode.R, since we specify that name. 
737 #+begin_src R :tangle Rcode.R :exports code
738 # tangle was specified, and a file name given (Rcode.R)
739 x <- 1:10
740 print(x)
741 #+end_src
743 Note that we will have multiple source code blocks in an org-mode
744 file, and they might have different types. For example, we might have
745 R and Python code in the same document, but different source blocks. 
747 This is no problem, as the tangling mechanism will generate
748 appropriate files of each type, containing only the code of that type.
750 Finally, you can specify the :tangle argument as a buffer-wide
751 setting, so that you don't have to specify it for every source code
752 block.
754 This opens up exciting possibilities like having a *single* org-mode
755 file that includes:
756 - all code for an R package
757 - all documentation for the package
758 - unit tests for the package
759 - material to generate slides for presentations, through org-beamer
760 - notes taken during package development 
761 - links to emails with bug reports, feature requests, etc. 
762 - a Makefile to build the package and documentation
764 ** Tangling the document 
766 Now that we have seen how to instruct org-mode how to produce source
767 code files from our org-mode document, how do we actually tangle the
768 document?
770 We simply have to call the org-babel-tangle function, bound by default
771 to C-c C-v C-t. 
773 Org-mode confirms in the minibuffer how many code blocks have been
774 tangled, and inspecting the file system should show that your source
775 code files have been created. There exists a hook function that will
776 run any post-processing programs you have defined, for example, a
777 compiler, `R CMD build`, or running `make` with a Makefile, possibly
778 itself generated from the org-mode document!
780 * Exporting documents containing code and results
782 Org-mode provides a rich set of functions and customizations for
783 exporting documents into more human-readable forms, and for users who
784 are not Emacs or org-mode users. The most common methods are
785 generating PDF documents through LaTeX, and HTML output. Source code
786 will be syntax highlighted, in HTML.  There are various options for
787 PDF, including using the listings package.
789 With org-mode source blocks, you can choose to export the source code,
790 the results of evaluating the source code, neither, or both.
791 The :exports header argument controls this. See the [[http://orgmode.org/manual/Exporting-code-blocks.html#Exporting-code-blocks][documentation]] for
792 further examples. 
794 As an example, type C-c C-e b to see an HTML version of this document.
796 Some fairly sophisticated processes, including complete report
797 generation using R graphics and tables, can be achieved through this
798 facility.
800 Using org-mode in this manner is essentially an alternative to Sweave,
801 with the advantages of:
802 - do not need to learn LaTeX or other markup language
803 - any future org-mode export engines will be available to you
804 - writing code in org-mode gives you access to a hyper-commenting
805   system, with features such as TODO items, in-document linking, tags, 
806   and code folding.
808 If you're an advanced LaTeX user, you probably don't view point 1
809 above as an advantage. :) 
811 Whether or not you use all the features that org-mode provides, you
812 can use the system for literate programming and reproducible research,
813 on projects large and small.
815 * Where to go from here? 
817 We have seen how to submit R code for evaluation in org-mode. There
818 are many good reasons to do this, including tying results to source
819 code, code folding, exporting of code and results into many common
820 formats, improving documentation, and the innumerable features that
821 org-mode provides, and will continue to provide in the future. 
823 As with all new processes, it can be a challenge to start working with
824 source code this way. As a current org-mode user, I think the
825 benefits are clear.
827 As for what to do next, try looking at the [[http://orgmode.org/worg/org-contrib/babel/uses.php][results]] of some of those
828 who use org-mode with org-babel to accomplish interesting things. You
829 can look at current documentation for R support [[http://orgmode.org/worg/org-contrib/babel/languages/ob-doc-R.php][here]].
831 For an exercise in using org-mode with source code, you can write your
832 Emacs initialization file in org-mode! These [[http://orgmode.org/worg/org-contrib/babel/intro.php#sec-8_2_1][instructions]] are slightly
833 out of date, but they give you a general idea of how to proceed.
834 Essentially, your master Emacs init file will simply tangle an
835 org-mode file full Emacs lisp code blocks, and then load the resulting
836 file. My Emacs init file is around 1000 lines long, so organizing it
837 in a hierarchy with embedded tags and links is very useful to me.
839 In short, there are many possibilities using these techniques! In many
840 ways, I have only scratched the surface of the capabilities of
841 org-mode in this tutorial. As always, the [[http://orgmode.org/manual/index.html#Top][official manual]] will be the
842 source of the most up-to-date information and features of this great
843 tool.