org-babel: further cleaning of parameter-passing to language files
[rgr-org-mode.git] / contrib / babel / lisp / langs / org-babel-R.el
blobf9e0d0048f28234b6aeb37a650a1ab6e59eeae8e
1 ;;; org-babel-R.el --- org-babel functions for R code evaluation
3 ;; Copyright (C) 2009 Eric Schulte
5 ;; Author: Eric Schulte
6 ;; Keywords: literate programming, reproducible research, R, statistics
7 ;; Homepage: http://orgmode.org
8 ;; Version: 0.01
10 ;;; License:
12 ;; This program is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 3, or (at your option)
15 ;; any later version.
17 ;; This program is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
27 ;;; Commentary:
29 ;; Org-Babel support for evaluating R code
31 ;;; Code:
32 (require 'org-babel)
34 (org-babel-add-interpreter "R")
36 (add-to-list 'org-babel-tangle-langs '("R" "R" "#!/usr/bin/env Rscript"))
38 (defun org-babel-execute:R (body params)
39 "Execute a block of R code with org-babel. This function is
40 called by `org-babel-execute-src-block'."
41 (message "executing R source code block...")
42 (save-window-excursion
43 (let* ((processed-params (org-babel-process-params params))
44 (result-type (fourth processed-params))
45 (session (org-babel-R-initiate-session (first processed-params)))
46 (vars (second processed-params))
47 (column-names-p (cdr (assoc :colnames params)))
48 (out-file (cdr (assoc :file params)))
49 (augmented-body
50 (concat
51 (if out-file (concat (org-babel-R-construct-graphics-device-call out-file params) "\n") "")
52 (mapconcat ;; define any variables
53 (lambda (pair) (org-babel-R-assign-elisp (car pair) (cdr pair))) vars "\n")
54 "\n" body "\n" (if out-file "dev.off()\n" "")))
55 (result (org-babel-R-evaluate session augmented-body result-type column-names-p)))
56 (or out-file result))))
58 (defun org-babel-prep-session:R (session params)
59 "Prepare SESSION according to the header arguments specified in PARAMS."
60 (let* ((session (org-babel-R-initiate-session session))
61 (vars (org-babel-ref-variables params)))
62 (mapc (lambda (pair) (org-babel-R-assign-elisp session (car pair) (cdr pair))) vars)))
64 ;; helper functions
66 (defun org-babel-R-quote-tsv-field (s)
67 "Quote field S for export to R."
68 (if (stringp s)
69 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
70 (format "%S" s)))
72 (defun org-babel-R-assign-elisp (name value)
73 "Read the elisp VALUE into a variable named NAME."
74 (if (listp value)
75 (let ((transition-file (make-temp-file "org-babel-R-import")))
76 ;; ensure VALUE has an orgtbl structure (depth of at least 2)
77 (unless (listp (car value)) (setq value (list value)))
78 (with-temp-file transition-file
79 (insert (orgtbl-to-tsv value '(:fmt org-babel-R-quote-tsv-field)))
80 (insert "\n"))
81 (format "%s <- read.table(\"%s\", header=%s, sep=\"\\t\", as.is=TRUE)"
82 name transition-file (if (eq (second value) 'hline) "TRUE" "FALSE")))
83 (format "%s <- %s" name (org-babel-R-quote-tsv-field value))))
85 (defun org-babel-R-initiate-session (session)
86 "If there is not a current R process then create one."
87 (unless (string= session "none")
88 (setq session (or session "*R*"))
89 (if (org-babel-comint-buffer-livep session)
90 session
91 (save-window-excursion
92 (R)
93 (rename-buffer (if (bufferp session) (buffer-name session)
94 (if (stringp session) session (buffer-name)))) (current-buffer)))))
96 (defun org-babel-R-construct-graphics-device-call (out-file params)
97 "Construct the call to the graphics device"
98 (let ((devices
99 '((:bmp . "bmp")
100 (:jpg . "jpeg")
101 (:jpeg . "jpeg")
102 (:tiff . "tiff")
103 (:png . "png")
104 (:pdf . "pdf")
105 (:ps . "postscript")
106 (:postscript . "postscript")))
107 (allowed-args '(:width :height :bg :units :pointsize
108 :antialias :quality :compression :res :type
109 :family :title :fonts :version :paper :encoding
110 :pagecentre :colormodel :useDingbats :horizontal))
111 (device (and (string-match ".+\\.\\([^.]+\\)" out-file) (match-string 1 out-file)))
112 (extra-args (cdr (assq :R-dev-args params))) filearg args)
113 (setq device (or (and device (cdr (assq (intern (concat ":" device)) devices))) "png"))
114 (setq filearg (if (member device '("pdf" "postscript")) "file" "filename"))
115 (setq args (mapconcat (lambda (pair)
116 (if (member (car pair) allowed-args)
117 (format ",%s=%s" (substring (symbol-name (car pair)) 1) (cdr pair)) ""))
118 params ""))
119 (format "%s(%s=\"%s\"%s%s%s)\n" device filearg out-file args (if extra-args "," "") (or extra-args ""))))
121 (defvar org-babel-R-eoe-indicator "'org_babel_R_eoe'")
122 (defvar org-babel-R-eoe-output "[1] \"org_babel_R_eoe\"")
123 (defvar org-babel-R-wrapper-method "main <- function ()\n{\n%s\n}
124 write.table(main(), file=\"%s\", sep=\"\\t\", na=\"nil\",row.names=FALSE, col.names=%s, quote=FALSE)")
126 (defun org-babel-R-evaluate (session body result-type column-names-p)
127 "Pass BODY to the R process in SESSION. If RESULT-TYPE equals
128 'output then return a list of the outputs of the statements in
129 BODY, if RESULT-TYPE equals 'value then return the value of the
130 last statement in BODY, as elisp."
131 (if (not session)
132 ;; external process evaluation
133 (let ((in-tmp-file (make-temp-file "R-in-functional-results"))
134 (out-tmp-file (make-temp-file "R-out-functional-results")))
135 (case result-type
136 (output
137 (with-temp-file in-tmp-file (insert body))
138 (shell-command-to-string (format "R --slave --no-save < '%s' > '%s'"
139 in-tmp-file out-tmp-file))
140 (with-temp-buffer (insert-file-contents out-tmp-file) (buffer-string)))
141 (value
142 (with-temp-file in-tmp-file
143 (insert (format org-babel-R-wrapper-method
144 body out-tmp-file (if column-names-p "TRUE" "FALSE"))))
145 (shell-command (format "R --no-save < '%s'" in-tmp-file))
146 (org-babel-R-process-value-result
147 (org-babel-import-elisp-from-file out-tmp-file) column-names-p))))
148 ;; comint session evaluation
149 (org-babel-comint-in-buffer session
150 (let* ((tmp-file (make-temp-file "org-babel-R"))
151 (full-body
152 (case result-type
153 (value
154 (mapconcat #'org-babel-chomp (list body
155 (format "write.table(.Last.value, file=\"%s\", sep=\"\\t\", na=\"nil\",row.names=FALSE, col.names=%s, quote=FALSE)" tmp-file (if column-names-p "TRUE" "FALSE"))
156 org-babel-R-eoe-indicator) "\n"))
157 (output
158 (mapconcat #'org-babel-chomp (list body org-babel-R-eoe-indicator) "\n"))))
159 (raw (org-babel-comint-with-output session org-babel-R-eoe-output nil
160 (insert full-body) (inferior-ess-send-input)))
161 (comint-prompt-regexp
162 (concat "^\\("
163 inferior-ess-primary-prompt
164 "\\|"
165 inferior-ess-secondary-prompt
166 "\\)*"))
167 broke results)
168 (case result-type
169 (value (org-babel-R-process-value-result
170 (org-babel-import-elisp-from-file tmp-file) column-names-p))
171 (output
172 (flet ((extractor
173 (el)
174 (if (or broke
175 (and (string-match (regexp-quote org-babel-R-eoe-output) el)
176 (setq broke t)))
178 (if (= (length el) 0)
180 (if (string-match comint-prompt-regexp el)
181 (substring el (match-end 0))
182 el)))))
183 (mapconcat
184 #'identity
185 (delete nil (mapcar #'extractor (mapcar #'org-babel-chomp raw))) "\n"))))))))
187 (defun org-babel-R-process-value-result (result column-names-p)
188 "R-specific processing of return value prior to return to org-babel.
190 Currently, insert hline if column names in output have been requested."
191 (if column-names-p
192 (cons (car result) (cons 'hline (cdr result)))
193 result))
196 (provide 'org-babel-R)
197 ;;; org-babel-R.el ends here