Revert "ob-R.el: Improve the capturing of output-type results in sessions."
[org-mode.git] / lisp / ob-R.el
blob9f4eb4b138d6f75bfde0b43b00a21f625784b7d3
1 ;;; ob-R.el --- org-babel functions for R code evaluation
3 ;; Copyright (C) 2009-2014 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 (eval-when-compile (require 'cl))
33 (declare-function orgtbl-to-tsv "org-table" (table params))
34 (declare-function R "ext:essd-r" (&optional start-args))
35 (declare-function inferior-ess-send-input "ext:ess-inf" ())
36 (declare-function ess-make-buffer-current "ext:ess-inf" ())
37 (declare-function ess-eval-buffer "ext:ess-inf" (vis))
38 (declare-function org-number-sequence "org-compat" (from &optional to inc))
39 (declare-function org-remove-if-not "org" (predicate seq))
40 (declare-function org-every "org" (pred seq))
42 (defconst org-babel-header-args:R
43 '((width . :any)
44 (height . :any)
45 (bg . :any)
46 (units . :any)
47 (pointsize . :any)
48 (antialias . :any)
49 (quality . :any)
50 (compression . :any)
51 (res . :any)
52 (type . :any)
53 (family . :any)
54 (title . :any)
55 (fonts . :any)
56 (version . :any)
57 (paper . :any)
58 (encoding . :any)
59 (pagecentre . :any)
60 (colormodel . :any)
61 (useDingbats . :any)
62 (horizontal . :any)
63 (results . ((file list vector table scalar verbatim)
64 (raw org html latex code pp wrap)
65 (replace silent append prepend)
66 (output value graphics))))
67 "R-specific header arguments.")
69 (defconst ob-R-safe-header-args
70 (append org-babel-safe-header-args
71 '(:width :height :bg :units :pointsize :antialias :quality
72 :compression :res :type :family :title :fonts
73 :version :paper :encoding :pagecentre :colormodel
74 :useDingbats :horizontal))
75 "Header args which are safe for R babel blocks.
77 See `org-babel-safe-header-args' for documentation of the format of
78 this variable.")
80 (defvar org-babel-default-header-args:R '())
81 (put 'org-babel-default-header-args:R 'safe-local-variable
82 (org-babel-header-args-safe-fn ob-R-safe-header-args))
84 (defcustom org-babel-R-command "R --slave --no-save"
85 "Name of command to use for executing R code."
86 :group 'org-babel
87 :version "24.1"
88 :type 'string)
90 (defvar ess-local-process-name) ; dynamically scoped
91 (defun org-babel-edit-prep:R (info)
92 (let ((session (cdr (assoc :session (nth 2 info)))))
93 (when (and session (string-match "^\\*\\(.+?\\)\\*$" session))
94 (save-match-data (org-babel-R-initiate-session session nil)))))
96 (defconst ob-R-transfer-variable-table-with-header
97 "%s <- local({
98 con <- textConnection(
101 res <- read.table(
102 con,
103 header = %s,
104 row.names = %s,
105 sep = \"\\t\",
106 as.is = TRUE
108 close(con)
111 "R code used to transfer a table defined as a variable from org to R.
112 This function is used when the table contains a header.")
114 (defconst ob-R-transfer-variable-table-without-header
115 "%s <- local({
116 con <- textConnection(
119 res <- read.table(
120 con,
121 header = %s,
122 row.names = %s,
123 sep = \"\\t\",
124 as.is = TRUE,
125 fill = TRUE,
126 col.names = paste(\"V\", seq_len(%d), sep =\"\")
128 close(con)
131 "R code used to transfer a table defined as a variable from org to R.
132 This function is used when the table does not contain a header.")
134 (defun org-babel-expand-body:R (body params &optional graphics-file)
135 "Expand BODY according to PARAMS, return the expanded body."
136 (mapconcat 'identity
137 (append
138 (when (cdr (assoc :prologue params))
139 (list (cdr (assoc :prologue params))))
140 (org-babel-variable-assignments:R params)
141 (list body)
142 (when (cdr (assoc :epilogue params))
143 (list (cdr (assoc :epilogue params)))))
144 "\n"))
146 (defun org-babel-execute:R (body params)
147 "Execute a block of R code.
148 This function is called by `org-babel-execute-src-block'."
149 (save-excursion
150 (let* ((result-params (cdr (assoc :result-params params)))
151 (result-type (cdr (assoc :result-type params)))
152 (session (org-babel-R-initiate-session
153 (cdr (assoc :session params)) params))
154 (colnames-p (cdr (assoc :colnames params)))
155 (rownames-p (cdr (assoc :rownames params)))
156 (graphics-file (and (member "graphics" (assq :result-params params))
157 (org-babel-graphical-output-file params)))
158 (full-body
159 (let ((inside
160 (list (org-babel-expand-body:R body params graphics-file))))
161 (mapconcat 'identity
162 (if graphics-file
163 (append
164 (list (org-babel-R-construct-graphics-device-call
165 graphics-file params))
166 inside
167 (list "},error=function(e){plot(x=-1:1, y=-1:1, type='n', xlab='', ylab='', axes=FALSE); text(x=0, y=0, labels=e$message, col='red'); paste('ERROR', e$message, sep=' : ')}); dev.off()"))
168 inside)
169 "\n")))
170 (result
171 (org-babel-R-evaluate
172 session full-body result-type result-params
173 (or (equal "yes" colnames-p)
174 (org-babel-pick-name
175 (cdr (assoc :colname-names params)) colnames-p))
176 (or (equal "yes" rownames-p)
177 (org-babel-pick-name
178 (cdr (assoc :rowname-names params)) rownames-p)))))
179 (if graphics-file nil result))))
181 (defun org-babel-prep-session:R (session params)
182 "Prepare SESSION according to the header arguments specified in PARAMS."
183 (let* ((session (org-babel-R-initiate-session session params))
184 (var-lines (org-babel-variable-assignments:R params)))
185 (org-babel-comint-in-buffer session
186 (mapc (lambda (var)
187 (end-of-line 1) (insert var) (comint-send-input nil t)
188 (org-babel-comint-wait-for-output session)) var-lines))
189 session))
191 (defun org-babel-load-session:R (session body params)
192 "Load BODY into SESSION."
193 (save-window-excursion
194 (let ((buffer (org-babel-prep-session:R session params)))
195 (with-current-buffer buffer
196 (goto-char (process-mark (get-buffer-process (current-buffer))))
197 (insert (org-babel-chomp body)))
198 buffer)))
200 ;; helper functions
202 (defun org-babel-variable-assignments:R (params)
203 "Return list of R statements assigning the block's variables."
204 (let ((vars (mapcar 'cdr (org-babel-get-header params :var))))
205 (mapcar
206 (lambda (pair)
207 (org-babel-R-assign-elisp
208 (car pair) (cdr pair)
209 (equal "yes" (cdr (assoc :colnames params)))
210 (equal "yes" (cdr (assoc :rownames params)))))
211 (mapcar
212 (lambda (i)
213 (cons (car (nth i vars))
214 (org-babel-reassemble-table
215 (cdr (nth i vars))
216 (cdr (nth i (cdr (assoc :colname-names params))))
217 (cdr (nth i (cdr (assoc :rowname-names params)))))))
218 (org-number-sequence 0 (1- (length vars)))))))
220 (defun org-babel-R-quote-tsv-field (s)
221 "Quote field S for export to R."
222 (if (stringp s)
223 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
224 (format "%S" s)))
226 (defun org-babel-R-assign-elisp (name value colnames-p rownames-p)
227 "Construct R code assigning the elisp VALUE to a variable named NAME."
228 (if (listp value)
229 (let* ((lengths (mapcar 'length (org-remove-if-not 'sequencep value)))
230 (max (if lengths (apply 'max lengths) 0))
231 (min (if lengths (apply 'min lengths) 0)))
232 ;; Ensure VALUE has an orgtbl structure (depth of at least 2).
233 (unless (listp (car value)) (setq value (list value)))
234 (let ((file (orgtbl-to-tsv value '(:fmt org-babel-R-quote-tsv-field)))
235 (header (if (or (eq (nth 1 value) 'hline) colnames-p)
236 "TRUE" "FALSE"))
237 (row-names (if rownames-p "1" "NULL")))
238 (if (= max min)
239 (format ob-R-transfer-variable-table-with-header
240 name file header row-names)
241 (format ob-R-transfer-variable-table-without-header
242 name file header row-names max))))
243 (cond ((integerp value) (format "%s <- %s" name (concat (number-to-string value) "L")))
244 ((floatp value) (format "%s <- %s" name value))
245 ((stringp value) (format "%s <- %S" name (org-no-properties value)))
246 (t (format "%s <- %S" name (prin1-to-string value))))))
249 (defvar ess-ask-for-ess-directory) ; dynamically scoped
250 (defun org-babel-R-initiate-session (session params)
251 "If there is not a current R process then create one."
252 (unless (string= session "none")
253 (let ((session (or session "*R*"))
254 (ess-ask-for-ess-directory
255 (and (and (boundp 'ess-ask-for-ess-directory) ess-ask-for-ess-directory)
256 (not (cdr (assoc :dir params))))))
257 (if (org-babel-comint-buffer-livep session)
258 session
259 (save-window-excursion
260 (when (get-buffer session)
261 ;; Session buffer exists, but with dead process
262 (set-buffer session))
263 (require 'ess) (R)
264 (rename-buffer
265 (if (bufferp session)
266 (buffer-name session)
267 (if (stringp session)
268 session
269 (buffer-name))))
270 (current-buffer))))))
272 (defun org-babel-R-associate-session (session)
273 "Associate R code buffer with an R session.
274 Make SESSION be the inferior ESS process associated with the
275 current code buffer."
276 (setq ess-local-process-name
277 (process-name (get-buffer-process session)))
278 (ess-make-buffer-current))
280 (defvar org-babel-R-graphics-devices
281 '((:bmp "bmp" "filename")
282 (:jpg "jpeg" "filename")
283 (:jpeg "jpeg" "filename")
284 (:tikz "tikz" "file")
285 (:tiff "tiff" "filename")
286 (:png "png" "filename")
287 (:svg "svg" "file")
288 (:pdf "pdf" "file")
289 (:ps "postscript" "file")
290 (:postscript "postscript" "file"))
291 "An alist mapping graphics file types to R functions.
293 Each member of this list is a list with three members:
294 1. the file extension of the graphics file, as an elisp :keyword
295 2. the R graphics device function to call to generate such a file
296 3. the name of the argument to this function which specifies the
297 file to write to (typically \"file\" or \"filename\")")
299 (defun org-babel-R-construct-graphics-device-call (out-file params)
300 "Construct the call to the graphics device."
301 (let* ((allowed-args '(:width :height :bg :units :pointsize
302 :antialias :quality :compression :res
303 :type :family :title :fonts :version
304 :paper :encoding :pagecentre :colormodel
305 :useDingbats :horizontal))
306 (device (and (string-match ".+\\.\\([^.]+\\)" out-file)
307 (match-string 1 out-file)))
308 (device-info (or (assq (intern (concat ":" device))
309 org-babel-R-graphics-devices)
310 (assq :png org-babel-R-graphics-devices)))
311 (extra-args (cdr (assq :R-dev-args params))) filearg args)
312 (setq device (nth 1 device-info))
313 (setq filearg (nth 2 device-info))
314 (setq args (mapconcat
315 (lambda (pair)
316 (if (member (car pair) allowed-args)
317 (format ",%s=%S"
318 (substring (symbol-name (car pair)) 1)
319 (cdr pair)) ""))
320 params ""))
321 (format "%s(%s=\"%s\"%s%s%s); tryCatch({"
322 device filearg out-file args
323 (if extra-args "," "") (or extra-args ""))))
325 (defvar org-babel-R-eoe-indicator "'org_babel_R_eoe'")
326 (defvar org-babel-R-eoe-output "[1] \"org_babel_R_eoe\"")
328 (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\")")
330 (defun org-babel-R-evaluate
331 (session body result-type result-params column-names-p row-names-p)
332 "Evaluate R code in BODY."
333 (if session
334 (org-babel-R-evaluate-session
335 session body result-type result-params column-names-p row-names-p)
336 (org-babel-R-evaluate-external-process
337 body result-type result-params column-names-p row-names-p)))
339 (defun org-babel-R-evaluate-external-process
340 (body result-type result-params column-names-p row-names-p)
341 "Evaluate BODY in external R process.
342 If RESULT-TYPE equals 'output then return standard output as a
343 string. If RESULT-TYPE equals 'value then return the value of the
344 last statement in BODY, as elisp."
345 (case result-type
346 (value
347 (let ((tmp-file (org-babel-temp-file "R-")))
348 (org-babel-eval org-babel-R-command
349 (format org-babel-R-write-object-command
350 (if row-names-p "TRUE" "FALSE")
351 (if column-names-p
352 (if row-names-p "NA" "TRUE")
353 "FALSE")
354 (format "{function ()\n{\n%s\n}}()" body)
355 (org-babel-process-file-name tmp-file 'noquote)))
356 (org-babel-R-process-value-result
357 (org-babel-result-cond result-params
358 (with-temp-buffer
359 (insert-file-contents tmp-file)
360 (buffer-string))
361 (org-babel-import-elisp-from-file tmp-file '(16)))
362 column-names-p)))
363 (output (org-babel-eval org-babel-R-command body))))
365 (defvar ess-eval-visibly-p)
367 (defun org-babel-R-evaluate-session
368 (session body result-type result-params column-names-p row-names-p)
369 "Evaluate BODY in SESSION.
370 If RESULT-TYPE equals 'output then return standard output as a
371 string. If RESULT-TYPE equals 'value then return the value of the
372 last statement in BODY, as elisp."
373 (case result-type
374 (value
375 (with-temp-buffer
376 (insert (org-babel-chomp body))
377 (let ((ess-local-process-name
378 (process-name (get-buffer-process session)))
379 (ess-eval-visibly-p nil))
380 (ess-eval-buffer nil)))
381 (let ((tmp-file (org-babel-temp-file "R-")))
382 (org-babel-comint-eval-invisibly-and-wait-for-file
383 session tmp-file
384 (format org-babel-R-write-object-command
385 (if row-names-p "TRUE" "FALSE")
386 (if column-names-p
387 (if row-names-p "NA" "TRUE")
388 "FALSE")
389 ".Last.value" (org-babel-process-file-name tmp-file 'noquote)))
390 (org-babel-R-process-value-result
391 (org-babel-result-cond result-params
392 (with-temp-buffer
393 (insert-file-contents tmp-file)
394 (buffer-string))
395 (org-babel-import-elisp-from-file tmp-file '(16)))
396 column-names-p)))
397 (output
398 (mapconcat
399 'org-babel-chomp
400 (butlast
401 (delq nil
402 (mapcar
403 (lambda (line) (when (> (length line) 0) line))
404 (mapcar
405 (lambda (line) ;; cleanup extra prompts left in output
406 (if (string-match
407 "^\\([ ]*[>+\\.][ ]?\\)+\\([[0-9]+\\|[ ]\\)" line)
408 (substring line (match-end 1))
409 line))
410 (org-babel-comint-with-output (session org-babel-R-eoe-output)
411 (insert (mapconcat 'org-babel-chomp
412 (list body org-babel-R-eoe-indicator)
413 "\n"))
414 (inferior-ess-send-input)))))) "\n"))))
416 (defun org-babel-R-process-value-result (result column-names-p)
417 "R-specific processing of return value.
418 Insert hline if column names in output have been requested."
419 (if column-names-p
420 (cons (car result) (cons 'hline (cdr result)))
421 result))
423 (provide 'ob-R)
427 ;;; ob-R.el ends here