1 ;;; ob-R.el --- Babel Functions for R -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2009-2016 Free Software Foundation, Inc.
5 ;; Author: Eric Schulte
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/>.
27 ;; Org-Babel support for evaluating R code
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
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
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."
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
101 con <- textConnection(
104 res <- utils::read.table(
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
120 con <- textConnection(
123 res <- utils::read.table(
130 col.names = paste(\"V\", seq_len(%d), sep =\"\")
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."
143 (when (cdr (assoc :prologue params
))
144 (list (cdr (assoc :prologue params
))))
145 (org-babel-variable-assignments:R params
)
147 (when (cdr (assoc :epilogue params
))
148 (list (cdr (assoc :epilogue params
)))))
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'."
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
)))
165 (list (org-babel-expand-body:R body params graphics-file
))))
169 (list (org-babel-R-construct-graphics-device-call
170 graphics-file params
))
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()"))
176 (org-babel-R-evaluate
177 session full-body result-type result-params
178 (or (equal "yes" colnames-p
)
180 (cdr (assoc :colname-names params
)) colnames-p
))
181 (or (equal "yes" rownames-p
)
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
192 (end-of-line 1) (insert var
) (comint-send-input nil t
)
193 (org-babel-comint-wait-for-output session
)) var-lines
))
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
)))
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
)))
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
)))))
218 (cons (car (nth i vars
))
219 (org-babel-reassemble-table
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."
228 (concat "\"" (mapconcat 'identity
(split-string 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."
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
)
242 (row-names (if rownames-p
"1" "NULL")))
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
)
265 (save-window-excursion
266 (when (get-buffer session
)
267 ;; Session buffer exists, but with dead process
268 (set-buffer session
))
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
)))
275 (if (bufferp session
)
276 (buffer-name session
)
277 (if (stringp session
)
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")
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
326 (if (member (car pair
) allowed-args
)
328 (substring (symbol-name (car pair
)) 1)
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) {
347 write.table(object, file=tfile, sep=\"\\t\",
348 na=\"nil\",row.names=%s,col.names=%s,
350 file.rename(tfile,transfer.file)
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."
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."
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")
391 (if row-names-p
"NA" "TRUE")
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
398 (insert-file-contents tmp-file
)
399 (org-babel-chomp (buffer-string) "\n"))
400 (org-babel-import-elisp-from-file tmp-file
'(16)))
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."
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
423 (format org-babel-R-write-object-command
424 (if row-names-p
"TRUE" "FALSE")
426 (if row-names-p
"NA" "TRUE")
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
432 (insert-file-contents tmp-file
)
433 (org-babel-chomp (buffer-string) "\n"))
434 (org-babel-import-elisp-from-file tmp-file
'(16)))
442 (lambda (line) (when (> (length line
) 0) line
))
444 (lambda (line) ;; cleanup extra prompts left in output
446 "^\\([>+.]\\([ ][>.+]\\)*[ ]\\)"
447 (car (split-string line
"\n")))
448 (substring line
(match-end 1))
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
)
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."
460 (cons (car result
) (cons 'hline
(cdr result
)))
467 ;;; ob-R.el ends here