Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / ob-R.el
blobbffa1a41ab4440f6894867a28b569de8f36e3b13
1 ;;; ob-R.el --- Babel Functions for R -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2009-2016 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 'cl-lib)
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 ess-wait-for-process "ext:ess-inf"
39 (&optional proc sec-prompt wait force-redisplay))
40 (declare-function org-number-sequence "org-compat" (from &optional to inc))
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 html latex org code pp drawer)
65 (replace silent none 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-current-process-name) ; dynamically scoped
91 (defvar ess-local-process-name) ; dynamically scoped
92 (defun org-babel-edit-prep:R (info)
93 (let ((session (cdr (assoc :session (nth 2 info)))))
94 (when (and session (string-match "^\\*\\(.+?\\)\\*$" session))
95 (save-match-data (org-babel-R-initiate-session session nil)))))
97 ;; The usage of utils::read.table() ensures that the command
98 ;; read.table() can be found even in circumstances when the utils
99 ;; package is not in the search path from R.
100 (defconst ob-R-transfer-variable-table-with-header
101 "%s <- local({
102 con <- textConnection(
105 res <- utils::read.table(
106 con,
107 header = %s,
108 row.names = %s,
109 sep = \"\\t\",
110 as.is = TRUE
112 close(con)
115 "R code used to transfer a table defined as a variable from org to R.
117 This function is used when the table contains a header.")
119 (defconst ob-R-transfer-variable-table-without-header
120 "%s <- local({
121 con <- textConnection(
124 res <- utils::read.table(
125 con,
126 header = %s,
127 row.names = %s,
128 sep = \"\\t\",
129 as.is = TRUE,
130 fill = TRUE,
131 col.names = paste(\"V\", seq_len(%d), sep =\"\")
133 close(con)
136 "R code used to transfer a table defined as a variable from org to R.
138 This function is used when the table does not contain a header.")
140 (defun org-babel-expand-body:R (body params &optional _graphics-file)
141 "Expand BODY according to PARAMS, return the expanded body."
142 (mapconcat 'identity
143 (append
144 (when (cdr (assoc :prologue params))
145 (list (cdr (assoc :prologue params))))
146 (org-babel-variable-assignments:R params)
147 (list body)
148 (when (cdr (assoc :epilogue params))
149 (list (cdr (assoc :epilogue params)))))
150 "\n"))
152 (defun org-babel-execute:R (body params)
153 "Execute a block of R code.
154 This function is called by `org-babel-execute-src-block'."
155 (save-excursion
156 (let* ((result-params (cdr (assoc :result-params params)))
157 (result-type (cdr (assoc :result-type params)))
158 (session (org-babel-R-initiate-session
159 (cdr (assoc :session params)) params))
160 (colnames-p (cdr (assoc :colnames params)))
161 (rownames-p (cdr (assoc :rownames params)))
162 (graphics-file (and (member "graphics" (assq :result-params params))
163 (org-babel-graphical-output-file params)))
164 (full-body
165 (let ((inside
166 (list (org-babel-expand-body:R body params graphics-file))))
167 (mapconcat 'identity
168 (if graphics-file
169 (append
170 (list (org-babel-R-construct-graphics-device-call
171 graphics-file params))
172 inside
173 (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()"))
174 inside)
175 "\n")))
176 (result
177 (org-babel-R-evaluate
178 session full-body result-type result-params
179 (or (equal "yes" colnames-p)
180 (org-babel-pick-name
181 (cdr (assoc :colname-names params)) colnames-p))
182 (or (equal "yes" rownames-p)
183 (org-babel-pick-name
184 (cdr (assoc :rowname-names params)) rownames-p)))))
185 (if graphics-file nil result))))
187 (defun org-babel-prep-session:R (session params)
188 "Prepare SESSION according to the header arguments specified in PARAMS."
189 (let* ((session (org-babel-R-initiate-session session params))
190 (var-lines (org-babel-variable-assignments:R params)))
191 (org-babel-comint-in-buffer session
192 (mapc (lambda (var)
193 (end-of-line 1) (insert var) (comint-send-input nil t)
194 (org-babel-comint-wait-for-output session)) var-lines))
195 session))
197 (defun org-babel-load-session:R (session body params)
198 "Load BODY into SESSION."
199 (save-window-excursion
200 (let ((buffer (org-babel-prep-session:R session params)))
201 (with-current-buffer buffer
202 (goto-char (process-mark (get-buffer-process (current-buffer))))
203 (insert (org-babel-chomp body)))
204 buffer)))
206 ;; helper functions
208 (defun org-babel-variable-assignments:R (params)
209 "Return list of R statements assigning the block's variables."
210 (let ((vars (org-babel--get-vars params)))
211 (mapcar
212 (lambda (pair)
213 (org-babel-R-assign-elisp
214 (car pair) (cdr pair)
215 (equal "yes" (cdr (assoc :colnames params)))
216 (equal "yes" (cdr (assoc :rownames params)))))
217 (mapcar
218 (lambda (i)
219 (cons (car (nth i vars))
220 (org-babel-reassemble-table
221 (cdr (nth i vars))
222 (cdr (nth i (cdr (assoc :colname-names params))))
223 (cdr (nth i (cdr (assoc :rowname-names params)))))))
224 (org-number-sequence 0 (1- (length vars)))))))
226 (defun org-babel-R-quote-tsv-field (s)
227 "Quote field S for export to R."
228 (if (stringp s)
229 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
230 (format "%S" s)))
232 (defun org-babel-R-assign-elisp (name value colnames-p rownames-p)
233 "Construct R code assigning the elisp VALUE to a variable named NAME."
234 (if (listp value)
235 (let* ((lengths (mapcar 'length (cl-remove-if-not 'sequencep value)))
236 (max (if lengths (apply 'max lengths) 0))
237 (min (if lengths (apply 'min lengths) 0)))
238 ;; Ensure VALUE has an orgtbl structure (depth of at least 2).
239 (unless (listp (car value)) (setq value (list value)))
240 (let ((file (orgtbl-to-tsv value '(:fmt org-babel-R-quote-tsv-field)))
241 (header (if (or (eq (nth 1 value) 'hline) colnames-p)
242 "TRUE" "FALSE"))
243 (row-names (if rownames-p "1" "NULL")))
244 (if (= max min)
245 (format ob-R-transfer-variable-table-with-header
246 name file header row-names)
247 (format ob-R-transfer-variable-table-without-header
248 name file header row-names max))))
249 (cond ((integerp value) (format "%s <- %s" name (concat (number-to-string value) "L")))
250 ((floatp value) (format "%s <- %s" name value))
251 ((stringp value) (format "%s <- %S" name (org-no-properties value)))
252 (t (format "%s <- %S" name (prin1-to-string value))))))
255 (defvar ess-ask-for-ess-directory) ; dynamically scoped
256 (defun org-babel-R-initiate-session (session params)
257 "If there is not a current R process then create one."
258 (unless (string= session "none")
259 (let ((session (or session "*R*"))
260 (ess-ask-for-ess-directory
261 (and (boundp 'ess-ask-for-ess-directory)
262 ess-ask-for-ess-directory
263 (not (cdr (assoc :dir params))))))
264 (if (org-babel-comint-buffer-livep session)
265 session
266 (save-window-excursion
267 (when (get-buffer session)
268 ;; Session buffer exists, but with dead process
269 (set-buffer session))
270 (require 'ess) (R)
271 (let ((R-proc (get-process (or ess-local-process-name
272 ess-current-process-name))))
273 (while (process-get R-proc 'callbacks)
274 (ess-wait-for-process R-proc)))
275 (rename-buffer
276 (if (bufferp session)
277 (buffer-name session)
278 (if (stringp session)
279 session
280 (buffer-name))))
281 (current-buffer))))))
283 (defun org-babel-R-associate-session (session)
284 "Associate R code buffer with an R session.
285 Make SESSION be the inferior ESS process associated with the
286 current code buffer."
287 (setq ess-local-process-name
288 (process-name (get-buffer-process session)))
289 (ess-make-buffer-current))
291 (defvar org-babel-R-graphics-devices
292 '((:bmp "bmp" "filename")
293 (:jpg "jpeg" "filename")
294 (:jpeg "jpeg" "filename")
295 (:tikz "tikz" "file")
296 (:tiff "tiff" "filename")
297 (:png "png" "filename")
298 (:svg "svg" "file")
299 (:pdf "pdf" "file")
300 (:ps "postscript" "file")
301 (:postscript "postscript" "file"))
302 "An alist mapping graphics file types to R functions.
304 Each member of this list is a list with three members:
305 1. the file extension of the graphics file, as an elisp :keyword
306 2. the R graphics device function to call to generate such a file
307 3. the name of the argument to this function which specifies the
308 file to write to (typically \"file\" or \"filename\")")
310 (defun org-babel-R-construct-graphics-device-call (out-file params)
311 "Construct the call to the graphics device."
312 (let* ((allowed-args '(:width :height :bg :units :pointsize
313 :antialias :quality :compression :res
314 :type :family :title :fonts :version
315 :paper :encoding :pagecentre :colormodel
316 :useDingbats :horizontal))
317 (device (and (string-match ".+\\.\\([^.]+\\)" out-file)
318 (match-string 1 out-file)))
319 (device-info (or (assq (intern (concat ":" device))
320 org-babel-R-graphics-devices)
321 (assq :png org-babel-R-graphics-devices)))
322 (extra-args (cdr (assq :R-dev-args params))) filearg args)
323 (setq device (nth 1 device-info))
324 (setq filearg (nth 2 device-info))
325 (setq args (mapconcat
326 (lambda (pair)
327 (if (member (car pair) allowed-args)
328 (format ",%s=%S"
329 (substring (symbol-name (car pair)) 1)
330 (cdr pair)) ""))
331 params ""))
332 (format "%s(%s=\"%s\"%s%s%s); tryCatch({"
333 device filearg out-file args
334 (if extra-args "," "") (or extra-args ""))))
336 (defconst org-babel-R-eoe-indicator "'org_babel_R_eoe'")
337 (defconst org-babel-R-eoe-output "[1] \"org_babel_R_eoe\"")
339 (defconst org-babel-R-write-object-command "{
340 function(object,transfer.file) {
341 object
342 invisible(
343 if (
344 inherits(
345 try(
347 tfile<-tempfile()
348 write.table(object, file=tfile, sep=\"\\t\",
349 na=\"nil\",row.names=%s,col.names=%s,
350 quote=FALSE)
351 file.rename(tfile,transfer.file)
353 silent=TRUE),
354 \"try-error\"))
356 if(!file.exists(transfer.file))
357 file.create(transfer.file)
361 }(object=%s,transfer.file=\"%s\")"
362 "A template for an R command to evaluate a block of code and write the result to a file.
364 Has four %s escapes to be filled in:
365 1. Row names, \"TRUE\" or \"FALSE\"
366 2. Column names, \"TRUE\" or \"FALSE\"
367 3. The code to be run (must be an expression, not a statement)
368 4. The name of the file to write to")
370 (defun org-babel-R-evaluate
371 (session body result-type result-params column-names-p row-names-p)
372 "Evaluate R code in BODY."
373 (if session
374 (org-babel-R-evaluate-session
375 session body result-type result-params column-names-p row-names-p)
376 (org-babel-R-evaluate-external-process
377 body result-type result-params column-names-p row-names-p)))
379 (defun org-babel-R-evaluate-external-process
380 (body result-type result-params column-names-p row-names-p)
381 "Evaluate BODY in external R process.
382 If RESULT-TYPE equals `output' then return standard output as a
383 string. If RESULT-TYPE equals `value' then return the value of the
384 last statement in BODY, as elisp."
385 (case result-type
386 (value
387 (let ((tmp-file (org-babel-temp-file "R-")))
388 (org-babel-eval org-babel-R-command
389 (format org-babel-R-write-object-command
390 (if row-names-p "TRUE" "FALSE")
391 (if column-names-p
392 (if row-names-p "NA" "TRUE")
393 "FALSE")
394 (format "{function ()\n{\n%s\n}}()" body)
395 (org-babel-process-file-name tmp-file 'noquote)))
396 (org-babel-R-process-value-result
397 (org-babel-result-cond result-params
398 (with-temp-buffer
399 (insert-file-contents tmp-file)
400 (org-babel-chomp (buffer-string) "\n"))
401 (org-babel-import-elisp-from-file tmp-file '(16)))
402 column-names-p)))
403 (output (org-babel-eval org-babel-R-command body))))
405 (defvar ess-eval-visibly-p)
407 (defun org-babel-R-evaluate-session
408 (session body result-type result-params column-names-p row-names-p)
409 "Evaluate BODY in SESSION.
410 If RESULT-TYPE equals `output' then return standard output as a
411 string. If RESULT-TYPE equals `value' then return the value of the
412 last statement in BODY, as elisp."
413 (case result-type
414 (value
415 (with-temp-buffer
416 (insert (org-babel-chomp body))
417 (let ((ess-local-process-name
418 (process-name (get-buffer-process session)))
419 (ess-eval-visibly-p nil))
420 (ess-eval-buffer nil)))
421 (let ((tmp-file (org-babel-temp-file "R-")))
422 (org-babel-comint-eval-invisibly-and-wait-for-file
423 session tmp-file
424 (format org-babel-R-write-object-command
425 (if row-names-p "TRUE" "FALSE")
426 (if column-names-p
427 (if row-names-p "NA" "TRUE")
428 "FALSE")
429 ".Last.value" (org-babel-process-file-name tmp-file 'noquote)))
430 (org-babel-R-process-value-result
431 (org-babel-result-cond result-params
432 (with-temp-buffer
433 (insert-file-contents tmp-file)
434 (org-babel-chomp (buffer-string) "\n"))
435 (org-babel-import-elisp-from-file tmp-file '(16)))
436 column-names-p)))
437 (output
438 (mapconcat
439 'org-babel-chomp
440 (butlast
441 (delq nil
442 (mapcar
443 (lambda (line) (when (> (length line) 0) line))
444 (mapcar
445 (lambda (line) ;; cleanup extra prompts left in output
446 (if (string-match
447 "^\\([>+.]\\([ ][>.+]\\)*[ ]\\)"
448 (car (split-string line "\n")))
449 (substring line (match-end 1))
450 line))
451 (org-babel-comint-with-output (session org-babel-R-eoe-output)
452 (insert (mapconcat 'org-babel-chomp
453 (list body org-babel-R-eoe-indicator)
454 "\n"))
455 (inferior-ess-send-input)))))) "\n"))))
457 (defun org-babel-R-process-value-result (result column-names-p)
458 "R-specific processing of return value.
459 Insert hline if column names in output have been requested."
460 (if column-names-p
461 (cons (car result) (cons 'hline (cdr result)))
462 result))
464 (provide 'ob-R)
468 ;;; ob-R.el ends here