babel: ob-perl is now using the new ob-eval functionality
[org-mode.git] / lisp / ob-R.el
blob325ad4ddb169ecd0250d0a82dc4d1b0388bb327e
1 ;;; ob-R.el --- org-babel functions for R code evaluation
3 ;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
5 ;; Author: Eric Schulte, Dan Davison
6 ;; Keywords: literate programming, reproducible research, R, statistics
7 ;; Homepage: http://orgmode.org
8 ;; Version: 0.01
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs 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 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs 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. If not, see <http://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;; Org-Babel support for evaluating R code
29 ;;; Code:
30 (require 'ob)
31 (require 'ob-ref)
32 (eval-when-compile (require 'cl))
34 (declare-function org-babel-comint-in-buffer "ob-comint" (buffer &rest body))
35 (declare-function comint-send-input "ob-comint" (el'.))
36 (declare-function org-babel-comint-wait-for-output "ob-comint" (buffer))
37 (declare-function org-babel-comint-buffer-livep "ob-comint" (buffer))
38 (declare-function org-babel-comint-with-output "ob-comint" (meta &rest body))
39 (declare-function orgtbl-to-tsv "ob-table" (table params))
40 (declare-function R "ext:essd-r" (&optional start-args))
41 (declare-function inferior-ess-send-input "ext:ess-inf" ())
43 (defconst org-babel-header-arg-names:R
44 '(width height bg units pointsize antialias quality compression
45 res type family title fonts version paper encoding
46 pagecentre colormodel useDingbats horizontal)
47 "R-specific header arguments.")
49 (defvar org-babel-default-header-args:R '())
51 (defvar org-babel-R-command "R --slave --no-save"
52 "Name of command to use for executing R code.")
54 (defun org-babel-expand-body:R (body params &optional processed-params)
55 "Expand BODY according to PARAMS, return the expanded body."
56 (let* ((processed-params (or processed-params
57 (org-babel-process-params params)))
58 (vars (mapcar
59 (lambda (i)
60 (cons (car (nth i (nth 1 processed-params)))
61 (org-babel-reassemble-table
62 (cdr (nth i (nth 1 processed-params)))
63 (cdr (nth i (nth 4 processed-params)))
64 (cdr (nth i (nth 5 processed-params))))))
65 (number-sequence 0 (1- (length (nth 1 processed-params))))))
66 (out-file (cdr (assoc :file params))))
67 (mapconcat ;; define any variables
68 #'org-babel-trim
69 ((lambda (inside)
70 (if out-file
71 (append
72 (org-babel-R-construct-graphics-device-call out-file params)
73 inside
74 (list "dev.off()"))
75 inside))
76 (append
77 (mapcar
78 (lambda (pair)
79 (org-babel-R-assign-elisp
80 (car pair) (cdr pair)
81 (equal "yes" (cdr (assoc :colnames params)))
82 (equal "yes" (cdr (assoc :rownames params)))))
83 vars)
84 (list body))) "\n")))
86 (defun org-babel-execute:R (body params)
87 "Execute a block of R code with org-babel. This function is
88 called by `org-babel-execute-src-block'."
89 (message "executing R source code block...")
90 (save-excursion
91 (let* ((processed-params (org-babel-process-params params))
92 (result-type (nth 3 processed-params))
93 (session (org-babel-R-initiate-session
94 (first processed-params) params))
95 (colnames-p (cdr (assoc :colnames params)))
96 (rownames-p (cdr (assoc :rownames params)))
97 (out-file (cdr (assoc :file params)))
98 (full-body (org-babel-expand-body:R body params processed-params))
99 (result
100 (org-babel-R-evaluate
101 session full-body result-type
102 (or (equal "yes" colnames-p)
103 (org-babel-pick-name (nth 4 processed-params) colnames-p))
104 (or (equal "yes" rownames-p)
105 (org-babel-pick-name (nth 5 processed-params) rownames-p)))))
106 (message "result is %S" result)
107 (or out-file result))))
109 (defun org-babel-prep-session:R (session params)
110 "Prepare SESSION according to the header arguments specified in PARAMS."
111 (let* ((session (org-babel-R-initiate-session session params))
112 (vars (org-babel-ref-variables params))
113 (var-lines
114 (mapcar
115 (lambda (pair) (org-babel-R-assign-elisp
116 (car pair) (cdr pair)
117 (equal (cdr (assoc :colnames params)) "yes")
118 (equal (cdr (assoc :rownames params)) "yes")))
119 vars)))
120 (org-babel-comint-in-buffer session
121 (mapc (lambda (var)
122 (end-of-line 1) (insert var) (comint-send-input nil t)
123 (org-babel-comint-wait-for-output session)) var-lines))
124 session))
126 (defun org-babel-load-session:R (session body params)
127 "Load BODY into SESSION."
128 (save-window-excursion
129 (let ((buffer (org-babel-prep-session:R session params)))
130 (with-current-buffer buffer
131 (goto-char (process-mark (get-buffer-process (current-buffer))))
132 (insert (org-babel-chomp body)))
133 buffer)))
135 ;; helper functions
137 (defun org-babel-R-quote-tsv-field (s)
138 "Quote field S for export to R."
139 (if (stringp s)
140 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
141 (format "%S" s)))
143 (defun org-babel-R-assign-elisp (name value colnames-p rownames-p)
144 "Construct R code assigning the elisp VALUE to a variable named NAME."
145 (if (listp value)
146 (let ((transition-file (make-temp-file "org-babel-R-import")))
147 ;; ensure VALUE has an orgtbl structure (depth of at least 2)
148 (unless (listp (car value)) (setq value (list value)))
149 (with-temp-file (org-babel-maybe-remote-file transition-file)
150 (insert (orgtbl-to-tsv value '(:fmt org-babel-R-quote-tsv-field)))
151 (insert "\n"))
152 (format "%s <- read.table(\"%s\", header=%s, row.names=%s, sep=\"\\t\", as.is=TRUE)"
153 name transition-file
154 (if (or (eq (nth 1 value) 'hline) colnames-p) "TRUE" "FALSE")
155 (if rownames-p "1" "NULL")))
156 (format "%s <- %s" name (org-babel-R-quote-tsv-field value))))
158 (defun org-babel-R-initiate-session (session params)
159 "If there is not a current R process then create one."
160 (unless (string= session "none")
161 (let ((session (or session "*R*"))
162 (ess-ask-for-ess-directory (not (cdr (assoc :dir params)))))
163 (if (org-babel-comint-buffer-livep session)
164 session
165 (save-window-excursion
166 (require 'ess) (R)
167 (rename-buffer
168 (if (bufferp session)
169 (buffer-name session)
170 (if (stringp session)
171 session
172 (buffer-name))))
173 (current-buffer))))))
175 (defun org-babel-R-construct-graphics-device-call (out-file params)
176 "Construct the call to the graphics device."
177 (let ((devices
178 '((:bmp . "bmp")
179 (:jpg . "jpeg")
180 (:jpeg . "jpeg")
181 (:tiff . "tiff")
182 (:png . "png")
183 (:svg . "svg")
184 (:pdf . "pdf")
185 (:ps . "postscript")
186 (:postscript . "postscript")))
187 (allowed-args '(:width :height :bg :units :pointsize
188 :antialias :quality :compression :res
189 :type :family :title :fonts :version
190 :paper :encoding :pagecentre :colormodel
191 :useDingbats :horizontal))
192 (device (and (string-match ".+\\.\\([^.]+\\)" out-file)
193 (match-string 1 out-file)))
194 (extra-args (cdr (assq :R-dev-args params))) filearg args)
195 (setq device (or (and device (cdr (assq (intern (concat ":" device))
196 devices))) "png"))
197 (setq filearg
198 (if (member device '("pdf" "postscript" "svg")) "file" "filename"))
199 (setq args (mapconcat
200 (lambda (pair)
201 (if (member (car pair) allowed-args)
202 (format ",%s=%s"
203 (substring (symbol-name (car pair)) 1)
204 (cdr pair)) ""))
205 params ""))
206 (format "%s(%s=\"%s\"%s%s%s)"
207 device filearg out-file args
208 (if extra-args "," "") (or extra-args ""))))
210 (defvar org-babel-R-eoe-indicator "'org_babel_R_eoe'")
211 (defvar org-babel-R-eoe-output "[1] \"org_babel_R_eoe\"")
212 (defvar org-babel-R-wrapper-method "main <- function ()\n{\n%s\n}
213 write.table(main(), file=\"%s\", sep=\"\\t\", na=\"nil\",row.names=%s, col.names=%s, quote=FALSE)")
214 (defvar org-babel-R-wrapper-lastvar "write.table(.Last.value, file=\"%s\", sep=\"\\t\", na=\"nil\",row.names=%s, col.names=%s, quote=FALSE)")
216 (defun org-babel-R-evaluate
217 (session body result-type column-names-p row-names-p)
218 "Pass BODY to the R process in SESSION. If RESULT-TYPE equals
219 'output then return a list of the outputs of the statements in
220 BODY, if RESULT-TYPE equals 'value then return the value of the
221 last statement in BODY, as elisp."
222 (if (not session)
223 ;; external process evaluation
224 (case result-type
225 (output (org-babel-eval org-babel-R-command body))
226 (value
227 (let ((tmp-file (make-temp-file "org-babel-R-results-")))
228 (org-babel-eval org-babel-R-command
229 (format org-babel-R-wrapper-method
230 body tmp-file
231 (if row-names-p "TRUE" "FALSE")
232 (if column-names-p
233 (if row-names-p "NA" "TRUE")
234 "FALSE")))
235 (org-babel-R-process-value-result
236 (org-babel-import-elisp-from-file
237 (org-babel-maybe-remote-file tmp-file)) column-names-p))))
238 ;; comint session evaluation
239 (case result-type
240 (value
241 (let ((tmp-file (make-temp-file "org-babel-R"))
242 broke)
243 (org-babel-comint-with-output (session org-babel-R-eoe-output)
244 (insert (mapconcat
245 #'org-babel-chomp
246 (list
247 body
248 (format org-babel-R-wrapper-lastvar
249 tmp-file
250 (if row-names-p "TRUE" "FALSE")
251 (if column-names-p
252 (if row-names-p "NA" "TRUE")
253 "FALSE"))
254 org-babel-R-eoe-indicator) "\n"))
255 (inferior-ess-send-input))
256 (org-babel-R-process-value-result
257 (org-babel-import-elisp-from-file
258 (org-babel-maybe-remote-file tmp-file)) column-names-p)))
259 (output
260 (mapconcat
261 #'org-babel-chomp
262 (butlast
263 (delq nil
264 (mapcar
265 #'identity
266 (org-babel-comint-with-output (session org-babel-R-eoe-output)
267 (insert (mapconcat #'org-babel-chomp
268 (list body org-babel-R-eoe-indicator)
269 "\n"))
270 (inferior-ess-send-input)))) 2) "\n")))))
272 (defun org-babel-R-process-value-result (result column-names-p)
273 "R-specific processing of return value prior to return to
274 org-babel. Insert hline if column names in output have been
275 requested."
276 (if column-names-p
277 (cons (car result) (cons 'hline (cdr result)))
278 result))
281 (provide 'ob-R)
283 ;; arch-tag: cd4c7298-503b-450f-a3c2-f3e74b630237
285 ;;; ob-R.el ends here