org-xhtml.el: Fix a crash during export of list-tables
[org-mode.git] / lisp / ob-R.el
blob09c895016d168f39bc86978fe9194b700b97b115
1 ;;; ob-R.el --- org-babel functions for R code evaluation
3 ;; Copyright (C) 2009-2011 Free Software Foundation, Inc.
5 ;; Author: Eric Schulte
6 ;; Dan Davison
7 ;; Keywords: literate programming, reproducible research, R, statistics
8 ;; Homepage: http://orgmode.org
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 (require 'ob-comint)
33 (require 'ob-eval)
34 (eval-when-compile (require 'cl))
36 (declare-function orgtbl-to-tsv "org-table" (table params))
37 (declare-function R "ext:essd-r" (&optional start-args))
38 (declare-function inferior-ess-send-input "ext:ess-inf" ())
39 (declare-function ess-make-buffer-current "ext:ess-inf" ())
40 (declare-function ess-eval-buffer "ext:ess-inf" (vis))
41 (declare-function org-number-sequence "org-compat" (from &optional to inc))
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 (defvar ess-local-process-name)
55 (defun org-babel-edit-prep:R (info)
56 (let ((session (cdr (assoc :session (nth 2 info)))))
57 (when (and session (string-match "^\\*\\(.+?\\)\\*$" session))
58 (save-match-data (org-babel-R-initiate-session session nil))
59 (setq ess-local-process-name (match-string 1 session)))))
61 (defun org-babel-expand-body:R (body params &optional graphics-file)
62 "Expand BODY according to PARAMS, return the expanded body."
63 (let ((graphics-file
64 (or graphics-file (org-babel-R-graphical-output-file params))))
65 (mapconcat
66 #'identity
67 ((lambda (inside)
68 (if graphics-file
69 (append
70 (list (org-babel-R-construct-graphics-device-call
71 graphics-file params))
72 inside
73 (list "dev.off()"))
74 inside))
75 (append (org-babel-variable-assignments:R params)
76 (list body))) "\n")))
78 (defun org-babel-execute:R (body params)
79 "Execute a block of R code.
80 This function is called by `org-babel-execute-src-block'."
81 (save-excursion
82 (let* ((result-type (cdr (assoc :result-type params)))
83 (session (org-babel-R-initiate-session
84 (cdr (assoc :session params)) params))
85 (colnames-p (cdr (assoc :colnames params)))
86 (rownames-p (cdr (assoc :rownames params)))
87 (graphics-file (org-babel-R-graphical-output-file params))
88 (full-body (org-babel-expand-body:R body params graphics-file))
89 (result
90 (org-babel-R-evaluate
91 session full-body result-type
92 (or (equal "yes" colnames-p)
93 (org-babel-pick-name
94 (cdr (assoc :colname-names params)) colnames-p))
95 (or (equal "yes" rownames-p)
96 (org-babel-pick-name
97 (cdr (assoc :rowname-names params)) rownames-p)))))
98 (if graphics-file nil result))))
100 (defun org-babel-prep-session:R (session params)
101 "Prepare SESSION according to the header arguments specified in PARAMS."
102 (let* ((session (org-babel-R-initiate-session session params))
103 (var-lines (org-babel-variable-assignments:R params)))
104 (org-babel-comint-in-buffer session
105 (mapc (lambda (var)
106 (end-of-line 1) (insert var) (comint-send-input nil t)
107 (org-babel-comint-wait-for-output session)) var-lines))
108 session))
110 (defun org-babel-load-session:R (session body params)
111 "Load BODY into SESSION."
112 (save-window-excursion
113 (let ((buffer (org-babel-prep-session:R session params)))
114 (with-current-buffer buffer
115 (goto-char (process-mark (get-buffer-process (current-buffer))))
116 (insert (org-babel-chomp body)))
117 buffer)))
119 ;; helper functions
121 (defun org-babel-variable-assignments:R (params)
122 "Return list of R statements assigning the block's variables"
123 (let ((vars (mapcar #'cdr (org-babel-get-header params :var))))
124 (mapcar
125 (lambda (pair)
126 (org-babel-R-assign-elisp
127 (car pair) (cdr pair)
128 (equal "yes" (cdr (assoc :colnames params)))
129 (equal "yes" (cdr (assoc :rownames params)))))
130 (mapcar
131 (lambda (i)
132 (cons (car (nth i vars))
133 (org-babel-reassemble-table
134 (cdr (nth i vars))
135 (cdr (nth i (cdr (assoc :colname-names params))))
136 (cdr (nth i (cdr (assoc :rowname-names params)))))))
137 (org-number-sequence 0 (1- (length vars)))))))
139 (defun org-babel-R-quote-tsv-field (s)
140 "Quote field S for export to R."
141 (if (stringp s)
142 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
143 (format "%S" s)))
145 (defun org-babel-R-assign-elisp (name value colnames-p rownames-p)
146 "Construct R code assigning the elisp VALUE to a variable named NAME."
147 (if (listp value)
148 (let ((transition-file (org-babel-temp-file "R-import-")))
149 ;; ensure VALUE has an orgtbl structure (depth of at least 2)
150 (unless (listp (car value)) (setq value (list value)))
151 (with-temp-file transition-file
152 (insert (orgtbl-to-tsv value '(:fmt org-babel-R-quote-tsv-field)))
153 (insert "\n"))
154 (format "%s <- read.table(\"%s\", header=%s, row.names=%s, sep=\"\\t\", as.is=TRUE)"
155 name (org-babel-process-file-name transition-file 'noquote)
156 (if (or (eq (nth 1 value) 'hline) colnames-p) "TRUE" "FALSE")
157 (if rownames-p "1" "NULL")))
158 (format "%s <- %s" name (org-babel-R-quote-tsv-field value))))
160 (defvar ess-ask-for-ess-directory nil)
161 (defun org-babel-R-initiate-session (session params)
162 "If there is not a current R process then create one."
163 (unless (string= session "none")
164 (let ((session (or session "*R*"))
165 (ess-ask-for-ess-directory
166 (and ess-ask-for-ess-directory (not (cdr (assoc :dir params))))))
167 (if (org-babel-comint-buffer-livep session)
168 session
169 (save-window-excursion
170 (require 'ess) (R)
171 (rename-buffer
172 (if (bufferp session)
173 (buffer-name session)
174 (if (stringp session)
175 session
176 (buffer-name))))
177 (current-buffer))))))
179 (defvar ess-local-process-name nil)
180 (defun org-babel-R-associate-session (session)
181 "Associate R code buffer with an R session.
182 Make SESSION be the inferior ESS process associated with the
183 current code buffer."
184 (setq ess-local-process-name
185 (process-name (get-buffer-process session)))
186 (ess-make-buffer-current))
188 (defun org-babel-R-graphical-output-file (params)
189 "Name of file to which R should send graphical output."
190 (and (member "graphics" (cdr (assq :result-params params)))
191 (cdr (assq :file params))))
193 (defun org-babel-R-construct-graphics-device-call (out-file params)
194 "Construct the call to the graphics device."
195 (let ((devices
196 '((:bmp . "bmp")
197 (:jpg . "jpeg")
198 (:jpeg . "jpeg")
199 (:tiff . "tiff")
200 (:png . "png")
201 (:svg . "svg")
202 (:pdf . "pdf")
203 (:ps . "postscript")
204 (:postscript . "postscript")))
205 (allowed-args '(:width :height :bg :units :pointsize
206 :antialias :quality :compression :res
207 :type :family :title :fonts :version
208 :paper :encoding :pagecentre :colormodel
209 :useDingbats :horizontal))
210 (device (and (string-match ".+\\.\\([^.]+\\)" out-file)
211 (match-string 1 out-file)))
212 (extra-args (cdr (assq :R-dev-args params))) filearg args)
213 (setq device (or (and device (cdr (assq (intern (concat ":" device))
214 devices))) "png"))
215 (setq filearg
216 (if (member device '("pdf" "postscript" "svg")) "file" "filename"))
217 (setq args (mapconcat
218 (lambda (pair)
219 (if (member (car pair) allowed-args)
220 (format ",%s=%s"
221 (substring (symbol-name (car pair)) 1)
222 (cdr pair)) ""))
223 params ""))
224 (format "%s(%s=\"%s\"%s%s%s)"
225 device filearg out-file args
226 (if extra-args "," "") (or extra-args ""))))
228 (defvar org-babel-R-eoe-indicator "'org_babel_R_eoe'")
229 (defvar org-babel-R-eoe-output "[1] \"org_babel_R_eoe\"")
231 (defvar org-babel-R-write-object-command "{function(object,transfer.file){object;invisible(if(inherits(try({tfile<-tempfile();write.table(object,file=tfile,sep=\"\\t\",na=\"nil\",row.names=%s,col.names=%s,quote=FALSE);file.rename(tfile,transfer.file)},silent=TRUE),\"try-error\")){if(!file.exists(transfer.file))file.create(transfer.file)})}}(object=%s,transfer.file=\"%s\")")
233 (defun org-babel-R-evaluate
234 (session body result-type column-names-p row-names-p)
235 "Evaluate R code in BODY."
236 (if session
237 (org-babel-R-evaluate-session
238 session body result-type column-names-p row-names-p)
239 (org-babel-R-evaluate-external-process
240 body result-type column-names-p row-names-p)))
242 (defun org-babel-R-evaluate-external-process
243 (body result-type column-names-p row-names-p)
244 "Evaluate BODY in external R process.
245 If RESULT-TYPE equals 'output then return standard output as a
246 string. If RESULT-TYPE equals 'value then return the value of the
247 last statement in BODY, as elisp."
248 (case result-type
249 (value
250 (let ((tmp-file (org-babel-temp-file "R-")))
251 (org-babel-eval org-babel-R-command
252 (format org-babel-R-write-object-command
253 (if row-names-p "TRUE" "FALSE")
254 (if column-names-p
255 (if row-names-p "NA" "TRUE")
256 "FALSE")
257 (format "{function ()\n{\n%s\n}}()" body)
258 (org-babel-process-file-name tmp-file 'noquote)))
259 (org-babel-R-process-value-result
260 (org-babel-import-elisp-from-file tmp-file '(16)) column-names-p)))
261 (output (org-babel-eval org-babel-R-command body))))
263 (defun org-babel-R-evaluate-session
264 (session body result-type column-names-p row-names-p)
265 "Evaluate BODY in SESSION.
266 If RESULT-TYPE equals 'output then return standard output as a
267 string. If RESULT-TYPE equals 'value then return the value of the
268 last statement in BODY, as elisp."
269 (case result-type
270 (value
271 (with-temp-buffer
272 (insert (org-babel-chomp body))
273 (let ((ess-local-process-name
274 (process-name (get-buffer-process session))))
275 (ess-eval-buffer nil)))
276 (let ((tmp-file (org-babel-temp-file "R-")))
277 (org-babel-comint-eval-invisibly-and-wait-for-file
278 session tmp-file
279 (format org-babel-R-write-object-command
280 (if row-names-p "TRUE" "FALSE")
281 (if column-names-p
282 (if row-names-p "NA" "TRUE")
283 "FALSE")
284 ".Last.value" (org-babel-process-file-name tmp-file 'noquote)))
285 (org-babel-R-process-value-result
286 (org-babel-import-elisp-from-file tmp-file '(16)) column-names-p)))
287 (output
288 (mapconcat
289 #'org-babel-chomp
290 (butlast
291 (delq nil
292 (mapcar
293 (lambda (line) (when (> (length line) 0) line))
294 (mapcar
295 (lambda (line) ;; cleanup extra prompts left in output
296 (if (string-match
297 "^\\([ ]*[>+\\.][ ]?\\)+\\([[0-9]+\\|[ ]\\)" line)
298 (substring line (match-end 1))
299 line))
300 (org-babel-comint-with-output (session org-babel-R-eoe-output)
301 (insert (mapconcat #'org-babel-chomp
302 (list body org-babel-R-eoe-indicator)
303 "\n"))
304 (inferior-ess-send-input)))))) "\n"))))
306 (defun org-babel-R-process-value-result (result column-names-p)
307 "R-specific processing of return value.
308 Insert hline if column names in output have been requested."
309 (if column-names-p
310 (cons (car result) (cons 'hline (cdr result)))
311 result))
313 (provide 'ob-R)
317 ;;; ob-R.el ends here