Mark `org-bound-and-true-p' as obsolete
[org-mode.git] / lisp / ob-R.el
blob1e71c8a3bce03f8221d0aca3e3d6f05f1bdbab6f
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))
41 (defconst org-babel-header-args:R
42 '((width . :any)
43 (height . :any)
44 (bg . :any)
45 (units . :any)
46 (pointsize . :any)
47 (antialias . :any)
48 (quality . :any)
49 (compression . :any)
50 (res . :any)
51 (type . :any)
52 (family . :any)
53 (title . :any)
54 (fonts . :any)
55 (version . :any)
56 (paper . :any)
57 (encoding . :any)
58 (pagecentre . :any)
59 (colormodel . :any)
60 (useDingbats . :any)
61 (horizontal . :any)
62 (results . ((file list vector table scalar verbatim)
63 (raw html latex org code pp drawer)
64 (replace silent none append prepend)
65 (output value graphics))))
66 "R-specific header arguments.")
68 (defconst ob-R-safe-header-args
69 (append org-babel-safe-header-args
70 '(:width :height :bg :units :pointsize :antialias :quality
71 :compression :res :type :family :title :fonts
72 :version :paper :encoding :pagecentre :colormodel
73 :useDingbats :horizontal))
74 "Header args which are safe for R babel blocks.
76 See `org-babel-safe-header-args' for documentation of the format of
77 this variable.")
79 (defvar org-babel-default-header-args:R '())
80 (put 'org-babel-default-header-args:R 'safe-local-variable
81 (org-babel-header-args-safe-fn ob-R-safe-header-args))
83 (defcustom org-babel-R-command "R --slave --no-save"
84 "Name of command to use for executing R code."
85 :group 'org-babel
86 :version "24.1"
87 :type 'string)
89 (defvar ess-current-process-name) ; dynamically scoped
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 ;; The usage of utils::read.table() ensures that the command
97 ;; read.table() can be found even in circumstances when the utils
98 ;; package is not in the search path from R.
99 (defconst ob-R-transfer-variable-table-with-header
100 "%s <- local({
101 con <- textConnection(
104 res <- utils::read.table(
105 con,
106 header = %s,
107 row.names = %s,
108 sep = \"\\t\",
109 as.is = TRUE
111 close(con)
114 "R code used to transfer a table defined as a variable from org to R.
116 This function is used when the table contains a header.")
118 (defconst ob-R-transfer-variable-table-without-header
119 "%s <- local({
120 con <- textConnection(
123 res <- utils::read.table(
124 con,
125 header = %s,
126 row.names = %s,
127 sep = \"\\t\",
128 as.is = TRUE,
129 fill = TRUE,
130 col.names = paste(\"V\", seq_len(%d), sep =\"\")
132 close(con)
135 "R code used to transfer a table defined as a variable from org to R.
137 This function is used when the table does not contain a header.")
139 (defun org-babel-expand-body:R (body params &optional _graphics-file)
140 "Expand BODY according to PARAMS, return the expanded body."
141 (mapconcat 'identity
142 (append
143 (when (cdr (assoc :prologue params))
144 (list (cdr (assoc :prologue params))))
145 (org-babel-variable-assignments:R params)
146 (list body)
147 (when (cdr (assoc :epilogue params))
148 (list (cdr (assoc :epilogue params)))))
149 "\n"))
151 (defun org-babel-execute:R (body params)
152 "Execute a block of R code.
153 This function is called by `org-babel-execute-src-block'."
154 (save-excursion
155 (let* ((result-params (cdr (assoc :result-params params)))
156 (result-type (cdr (assoc :result-type params)))
157 (session (org-babel-R-initiate-session
158 (cdr (assoc :session params)) params))
159 (colnames-p (cdr (assoc :colnames params)))
160 (rownames-p (cdr (assoc :rownames params)))
161 (graphics-file (and (member "graphics" (assq :result-params params))
162 (org-babel-graphical-output-file params)))
163 (full-body
164 (let ((inside
165 (list (org-babel-expand-body:R body params graphics-file))))
166 (mapconcat 'identity
167 (if graphics-file
168 (append
169 (list (org-babel-R-construct-graphics-device-call
170 graphics-file params))
171 inside
172 (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()"))
173 inside)
174 "\n")))
175 (result
176 (org-babel-R-evaluate
177 session full-body result-type result-params
178 (or (equal "yes" colnames-p)
179 (org-babel-pick-name
180 (cdr (assoc :colname-names params)) colnames-p))
181 (or (equal "yes" rownames-p)
182 (org-babel-pick-name
183 (cdr (assoc :rowname-names params)) rownames-p)))))
184 (if graphics-file nil result))))
186 (defun org-babel-prep-session:R (session params)
187 "Prepare SESSION according to the header arguments specified in PARAMS."
188 (let* ((session (org-babel-R-initiate-session session params))
189 (var-lines (org-babel-variable-assignments:R params)))
190 (org-babel-comint-in-buffer session
191 (mapc (lambda (var)
192 (end-of-line 1) (insert var) (comint-send-input nil t)
193 (org-babel-comint-wait-for-output session)) var-lines))
194 session))
196 (defun org-babel-load-session:R (session body params)
197 "Load BODY into SESSION."
198 (save-window-excursion
199 (let ((buffer (org-babel-prep-session:R session params)))
200 (with-current-buffer buffer
201 (goto-char (process-mark (get-buffer-process (current-buffer))))
202 (insert (org-babel-chomp body)))
203 buffer)))
205 ;; helper functions
207 (defun org-babel-variable-assignments:R (params)
208 "Return list of R statements assigning the block's variables."
209 (let ((vars (org-babel--get-vars params)))
210 (mapcar
211 (lambda (pair)
212 (org-babel-R-assign-elisp
213 (car pair) (cdr pair)
214 (equal "yes" (cdr (assoc :colnames params)))
215 (equal "yes" (cdr (assoc :rownames params)))))
216 (mapcar
217 (lambda (i)
218 (cons (car (nth i vars))
219 (org-babel-reassemble-table
220 (cdr (nth i vars))
221 (cdr (nth i (cdr (assoc :colname-names params))))
222 (cdr (nth i (cdr (assoc :rowname-names params)))))))
223 (number-sequence 0 (1- (length vars)))))))
225 (defun org-babel-R-quote-tsv-field (s)
226 "Quote field S for export to R."
227 (if (stringp s)
228 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
229 (format "%S" s)))
231 (defun org-babel-R-assign-elisp (name value colnames-p rownames-p)
232 "Construct R code assigning the elisp VALUE to a variable named NAME."
233 (if (listp value)
234 (let* ((lengths (mapcar 'length (cl-remove-if-not 'sequencep value)))
235 (max (if lengths (apply 'max lengths) 0))
236 (min (if lengths (apply 'min lengths) 0)))
237 ;; Ensure VALUE has an orgtbl structure (depth of at least 2).
238 (unless (listp (car value)) (setq value (list value)))
239 (let ((file (orgtbl-to-tsv value '(:fmt org-babel-R-quote-tsv-field)))
240 (header (if (or (eq (nth 1 value) 'hline) colnames-p)
241 "TRUE" "FALSE"))
242 (row-names (if rownames-p "1" "NULL")))
243 (if (= max min)
244 (format ob-R-transfer-variable-table-with-header
245 name file header row-names)
246 (format ob-R-transfer-variable-table-without-header
247 name file header row-names max))))
248 (cond ((integerp value) (format "%s <- %s" name (concat (number-to-string value) "L")))
249 ((floatp value) (format "%s <- %s" name value))
250 ((stringp value) (format "%s <- %S" name (org-no-properties value)))
251 (t (format "%s <- %S" name (prin1-to-string value))))))
254 (defvar ess-ask-for-ess-directory) ; dynamically scoped
255 (defun org-babel-R-initiate-session (session params)
256 "If there is not a current R process then create one."
257 (unless (string= session "none")
258 (let ((session (or session "*R*"))
259 (ess-ask-for-ess-directory
260 (and (boundp 'ess-ask-for-ess-directory)
261 ess-ask-for-ess-directory
262 (not (cdr (assoc :dir params))))))
263 (if (org-babel-comint-buffer-livep session)
264 session
265 (save-window-excursion
266 (when (get-buffer session)
267 ;; Session buffer exists, but with dead process
268 (set-buffer session))
269 (require 'ess) (R)
270 (let ((R-proc (get-process (or ess-local-process-name
271 ess-current-process-name))))
272 (while (process-get R-proc 'callbacks)
273 (ess-wait-for-process R-proc)))
274 (rename-buffer
275 (if (bufferp session)
276 (buffer-name session)
277 (if (stringp session)
278 session
279 (buffer-name))))
280 (current-buffer))))))
282 (defun org-babel-R-associate-session (session)
283 "Associate R code buffer with an R session.
284 Make SESSION be the inferior ESS process associated with the
285 current code buffer."
286 (setq ess-local-process-name
287 (process-name (get-buffer-process session)))
288 (ess-make-buffer-current))
290 (defvar org-babel-R-graphics-devices
291 '((:bmp "bmp" "filename")
292 (:jpg "jpeg" "filename")
293 (:jpeg "jpeg" "filename")
294 (:tikz "tikz" "file")
295 (:tiff "tiff" "filename")
296 (:png "png" "filename")
297 (:svg "svg" "file")
298 (:pdf "pdf" "file")
299 (:ps "postscript" "file")
300 (:postscript "postscript" "file"))
301 "An alist mapping graphics file types to R functions.
303 Each member of this list is a list with three members:
304 1. the file extension of the graphics file, as an elisp :keyword
305 2. the R graphics device function to call to generate such a file
306 3. the name of the argument to this function which specifies the
307 file to write to (typically \"file\" or \"filename\")")
309 (defun org-babel-R-construct-graphics-device-call (out-file params)
310 "Construct the call to the graphics device."
311 (let* ((allowed-args '(:width :height :bg :units :pointsize
312 :antialias :quality :compression :res
313 :type :family :title :fonts :version
314 :paper :encoding :pagecentre :colormodel
315 :useDingbats :horizontal))
316 (device (and (string-match ".+\\.\\([^.]+\\)" out-file)
317 (match-string 1 out-file)))
318 (device-info (or (assq (intern (concat ":" device))
319 org-babel-R-graphics-devices)
320 (assq :png org-babel-R-graphics-devices)))
321 (extra-args (cdr (assq :R-dev-args params))) filearg args)
322 (setq device (nth 1 device-info))
323 (setq filearg (nth 2 device-info))
324 (setq args (mapconcat
325 (lambda (pair)
326 (if (member (car pair) allowed-args)
327 (format ",%s=%S"
328 (substring (symbol-name (car pair)) 1)
329 (cdr pair)) ""))
330 params ""))
331 (format "%s(%s=\"%s\"%s%s%s); tryCatch({"
332 device filearg out-file args
333 (if extra-args "," "") (or extra-args ""))))
335 (defconst org-babel-R-eoe-indicator "'org_babel_R_eoe'")
336 (defconst org-babel-R-eoe-output "[1] \"org_babel_R_eoe\"")
338 (defconst org-babel-R-write-object-command "{
339 function(object,transfer.file) {
340 object
341 invisible(
342 if (
343 inherits(
344 try(
346 tfile<-tempfile()
347 write.table(object, file=tfile, sep=\"\\t\",
348 na=\"nil\",row.names=%s,col.names=%s,
349 quote=FALSE)
350 file.rename(tfile,transfer.file)
352 silent=TRUE),
353 \"try-error\"))
355 if(!file.exists(transfer.file))
356 file.create(transfer.file)
360 }(object=%s,transfer.file=\"%s\")"
361 "A template for an R command to evaluate a block of code and write the result to a file.
363 Has four %s escapes to be filled in:
364 1. Row names, \"TRUE\" or \"FALSE\"
365 2. Column names, \"TRUE\" or \"FALSE\"
366 3. The code to be run (must be an expression, not a statement)
367 4. The name of the file to write to")
369 (defun org-babel-R-evaluate
370 (session body result-type result-params column-names-p row-names-p)
371 "Evaluate R code in BODY."
372 (if session
373 (org-babel-R-evaluate-session
374 session body result-type result-params column-names-p row-names-p)
375 (org-babel-R-evaluate-external-process
376 body result-type result-params column-names-p row-names-p)))
378 (defun org-babel-R-evaluate-external-process
379 (body result-type result-params column-names-p row-names-p)
380 "Evaluate BODY in external R process.
381 If RESULT-TYPE equals `output' then return standard output as a
382 string. If RESULT-TYPE equals `value' then return the value of the
383 last statement in BODY, as elisp."
384 (case result-type
385 (value
386 (let ((tmp-file (org-babel-temp-file "R-")))
387 (org-babel-eval org-babel-R-command
388 (format org-babel-R-write-object-command
389 (if row-names-p "TRUE" "FALSE")
390 (if column-names-p
391 (if row-names-p "NA" "TRUE")
392 "FALSE")
393 (format "{function ()\n{\n%s\n}}()" body)
394 (org-babel-process-file-name tmp-file 'noquote)))
395 (org-babel-R-process-value-result
396 (org-babel-result-cond result-params
397 (with-temp-buffer
398 (insert-file-contents tmp-file)
399 (org-babel-chomp (buffer-string) "\n"))
400 (org-babel-import-elisp-from-file tmp-file '(16)))
401 column-names-p)))
402 (output (org-babel-eval org-babel-R-command body))))
404 (defvar ess-eval-visibly-p)
406 (defun org-babel-R-evaluate-session
407 (session body result-type result-params column-names-p row-names-p)
408 "Evaluate BODY in SESSION.
409 If RESULT-TYPE equals `output' then return standard output as a
410 string. If RESULT-TYPE equals `value' then return the value of the
411 last statement in BODY, as elisp."
412 (case result-type
413 (value
414 (with-temp-buffer
415 (insert (org-babel-chomp body))
416 (let ((ess-local-process-name
417 (process-name (get-buffer-process session)))
418 (ess-eval-visibly-p nil))
419 (ess-eval-buffer nil)))
420 (let ((tmp-file (org-babel-temp-file "R-")))
421 (org-babel-comint-eval-invisibly-and-wait-for-file
422 session tmp-file
423 (format org-babel-R-write-object-command
424 (if row-names-p "TRUE" "FALSE")
425 (if column-names-p
426 (if row-names-p "NA" "TRUE")
427 "FALSE")
428 ".Last.value" (org-babel-process-file-name tmp-file 'noquote)))
429 (org-babel-R-process-value-result
430 (org-babel-result-cond result-params
431 (with-temp-buffer
432 (insert-file-contents tmp-file)
433 (org-babel-chomp (buffer-string) "\n"))
434 (org-babel-import-elisp-from-file tmp-file '(16)))
435 column-names-p)))
436 (output
437 (mapconcat
438 'org-babel-chomp
439 (butlast
440 (delq nil
441 (mapcar
442 (lambda (line) (when (> (length line) 0) line))
443 (mapcar
444 (lambda (line) ;; cleanup extra prompts left in output
445 (if (string-match
446 "^\\([>+.]\\([ ][>.+]\\)*[ ]\\)"
447 (car (split-string line "\n")))
448 (substring line (match-end 1))
449 line))
450 (org-babel-comint-with-output (session org-babel-R-eoe-output)
451 (insert (mapconcat 'org-babel-chomp
452 (list body org-babel-R-eoe-indicator)
453 "\n"))
454 (inferior-ess-send-input)))))) "\n"))))
456 (defun org-babel-R-process-value-result (result column-names-p)
457 "R-specific processing of return value.
458 Insert hline if column names in output have been requested."
459 (if column-names-p
460 (cons (car result) (cons 'hline (cdr result)))
461 result))
463 (provide 'ob-R)
467 ;;; ob-R.el ends here