1 ;;; ob-R.el --- org-babel functions for R code evaluation
3 ;; Copyright (C) 2009-2014 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
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
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
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."
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 (defun org-babel-expand-body:R
(body params
&optional graphics-file
)
97 "Expand BODY according to PARAMS, return the expanded body."
99 (or graphics-file
(org-babel-R-graphical-output-file params
))))
100 (mapconcat #'identity
102 (when (cdr (assoc :prologue params
))
103 (list (cdr (assoc :prologue params
))))
104 (org-babel-variable-assignments:R params
)
106 (when (cdr (assoc :epilogue params
))
107 (list (cdr (assoc :epilogue params
)))))
110 (defun org-babel-execute:R
(body params
)
111 "Execute a block of R code.
112 This function is called by `org-babel-execute-src-block'."
114 (let* ((result-params (cdr (assoc :result-params params
)))
115 (result-type (cdr (assoc :result-type params
)))
116 (session (org-babel-R-initiate-session
117 (cdr (assoc :session params
)) params
))
118 (colnames-p (cdr (assoc :colnames params
)))
119 (rownames-p (cdr (assoc :rownames params
)))
120 (graphics-file (org-babel-R-graphical-output-file params
))
123 (list (org-babel-expand-body:R body params graphics-file
))))
124 (mapconcat #'identity
127 (list (org-babel-R-construct-graphics-device-call
128 graphics-file params
))
130 (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()"))
134 (org-babel-R-evaluate
135 session full-body result-type result-params
136 (or (equal "yes" colnames-p
)
138 (cdr (assoc :colname-names params
)) colnames-p
))
139 (or (equal "yes" rownames-p
)
141 (cdr (assoc :rowname-names params
)) rownames-p
)))))
142 (if graphics-file nil result
))))
144 (defun org-babel-prep-session:R
(session params
)
145 "Prepare SESSION according to the header arguments specified in PARAMS."
146 (let* ((session (org-babel-R-initiate-session session params
))
147 (var-lines (org-babel-variable-assignments:R params
)))
148 (org-babel-comint-in-buffer session
150 (end-of-line 1) (insert var
) (comint-send-input nil t
)
151 (org-babel-comint-wait-for-output session
)) var-lines
))
154 (defun org-babel-load-session:R
(session body params
)
155 "Load BODY into SESSION."
156 (save-window-excursion
157 (let ((buffer (org-babel-prep-session:R session params
)))
158 (with-current-buffer buffer
159 (goto-char (process-mark (get-buffer-process (current-buffer))))
160 (insert (org-babel-chomp body
)))
165 (defun org-babel-variable-assignments:R
(params)
166 "Return list of R statements assigning the block's variables."
167 (let ((vars (mapcar #'cdr
(org-babel-get-header params
:var
))))
170 (org-babel-R-assign-elisp
171 (car pair
) (cdr pair
)
172 (equal "yes" (cdr (assoc :colnames params
)))
173 (equal "yes" (cdr (assoc :rownames params
)))))
176 (cons (car (nth i vars
))
177 (org-babel-reassemble-table
179 (cdr (nth i
(cdr (assoc :colname-names params
))))
180 (cdr (nth i
(cdr (assoc :rowname-names params
)))))))
181 (org-number-sequence 0 (1- (length vars
)))))))
183 (defun org-babel-R-quote-tsv-field (s)
184 "Quote field S for export to R."
186 (concat "\"" (mapconcat 'identity
(split-string s
"\"") "\"\"") "\"")
189 (defun org-babel-R-assign-elisp (name value colnames-p rownames-p
)
190 "Construct R code assigning the elisp VALUE to a variable named NAME."
192 (let ((max (apply #'max
(mapcar #'length
(org-remove-if-not
193 #'sequencep value
))))
194 (min (apply #'min
(mapcar #'length
(org-remove-if-not
195 #'sequencep value
))))
196 (transition-file (org-babel-temp-file "R-import-")))
197 ;; ensure VALUE has an orgtbl structure (depth of at least 2)
198 (unless (listp (car value
)) (setq value
(list value
)))
199 (with-temp-file transition-file
201 (orgtbl-to-tsv value
'(:fmt org-babel-R-quote-tsv-field
))
203 (let ((file (org-babel-process-file-name transition-file
'noquote
))
204 (header (if (or (eq (nth 1 value
) 'hline
) colnames-p
)
206 (row-names (if rownames-p
"1" "NULL")))
208 (format "%s <- read.table(\"%s\",
212 as.is=TRUE)" name file header row-names
)
213 (format "%s <- read.table(\"%s\",
219 col.names = paste(\"V\", seq_len(%d), sep =\"\"))"
220 name file header row-names max
))))
221 (format "%s <- %s" name
(org-babel-R-quote-tsv-field value
))))
223 (defvar ess-ask-for-ess-directory
) ; dynamically scoped
224 (defun org-babel-R-initiate-session (session params
)
225 "If there is not a current R process then create one."
226 (unless (string= session
"none")
227 (let ((session (or session
"*R*"))
228 (ess-ask-for-ess-directory
229 (and (and (boundp 'ess-ask-for-ess-directory
) ess-ask-for-ess-directory
)
230 (not (cdr (assoc :dir params
))))))
231 (if (org-babel-comint-buffer-livep session
)
233 (save-window-excursion
234 (when (get-buffer session
)
235 ;; Session buffer exists, but with dead process
236 (set-buffer session
))
239 (if (bufferp session
)
240 (buffer-name session
)
241 (if (stringp session
)
244 (current-buffer))))))
246 (defun org-babel-R-associate-session (session)
247 "Associate R code buffer with an R session.
248 Make SESSION be the inferior ESS process associated with the
249 current code buffer."
250 (setq ess-local-process-name
251 (process-name (get-buffer-process session
)))
252 (ess-make-buffer-current))
254 (defun org-babel-R-graphical-output-file (params)
255 "Name of file to which R should send graphical output."
256 (and (member "graphics" (cdr (assq :result-params params
)))
257 (cdr (assq :file params
))))
259 (defvar org-babel-R-graphics-devices
260 '((:bmp
"bmp" "filename")
261 (:jpg
"jpeg" "filename")
262 (:jpeg
"jpeg" "filename")
263 (:tikz
"tikz" "file")
264 (:tiff
"tiff" "filename")
265 (:png
"png" "filename")
268 (:ps
"postscript" "file")
269 (:postscript
"postscript" "file"))
270 "An alist mapping graphics file types to R functions.
272 Each member of this list is a list with three members:
273 1. the file extension of the graphics file, as an elisp :keyword
274 2. the R graphics device function to call to generate such a file
275 3. the name of the argument to this function which specifies the
276 file to write to (typically \"file\" or \"filename\")")
278 (defun org-babel-R-construct-graphics-device-call (out-file params
)
279 "Construct the call to the graphics device."
280 (let* ((allowed-args '(:width
:height
:bg
:units
:pointsize
281 :antialias
:quality
:compression
:res
282 :type
:family
:title
:fonts
:version
283 :paper
:encoding
:pagecentre
:colormodel
284 :useDingbats
:horizontal
))
285 (device (and (string-match ".+\\.\\([^.]+\\)" out-file
)
286 (match-string 1 out-file
)))
287 (device-info (or (assq (intern (concat ":" device
))
288 org-babel-R-graphics-devices
)
289 (assq :png org-babel-R-graphics-devices
)))
290 (extra-args (cdr (assq :R-dev-args params
))) filearg args
)
291 (setq device
(nth 1 device-info
))
292 (setq filearg
(nth 2 device-info
))
293 (setq args
(mapconcat
295 (if (member (car pair
) allowed-args
)
297 (substring (symbol-name (car pair
)) 1)
300 (format "%s(%s=\"%s\"%s%s%s); tryCatch({"
301 device filearg out-file args
302 (if extra-args
"," "") (or extra-args
""))))
304 (defvar org-babel-R-eoe-indicator
"'org_babel_R_eoe'")
305 (defvar org-babel-R-eoe-output
"[1] \"org_babel_R_eoe\"")
307 (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\")")
309 (defun org-babel-R-evaluate
310 (session body result-type result-params column-names-p row-names-p
)
311 "Evaluate R code in BODY."
313 (org-babel-R-evaluate-session
314 session body result-type result-params column-names-p row-names-p
)
315 (org-babel-R-evaluate-external-process
316 body result-type result-params column-names-p row-names-p
)))
318 (defun org-babel-R-evaluate-external-process
319 (body result-type result-params column-names-p row-names-p
)
320 "Evaluate BODY in external R process.
321 If RESULT-TYPE equals 'output then return standard output as a
322 string. If RESULT-TYPE equals 'value then return the value of the
323 last statement in BODY, as elisp."
326 (let ((tmp-file (org-babel-temp-file "R-")))
327 (org-babel-eval org-babel-R-command
328 (format org-babel-R-write-object-command
329 (if row-names-p
"TRUE" "FALSE")
331 (if row-names-p
"NA" "TRUE")
333 (format "{function ()\n{\n%s\n}}()" body
)
334 (org-babel-process-file-name tmp-file
'noquote
)))
335 (org-babel-R-process-value-result
336 (org-babel-result-cond result-params
338 (insert-file-contents tmp-file
)
340 (org-babel-import-elisp-from-file tmp-file
'(16)))
342 (output (org-babel-eval org-babel-R-command body
))))
344 (defvar ess-eval-visibly-p
)
346 (defun org-babel-R-evaluate-session
347 (session body result-type result-params column-names-p row-names-p
)
348 "Evaluate BODY in SESSION.
349 If RESULT-TYPE equals 'output then return standard output as a
350 string. If RESULT-TYPE equals 'value then return the value of the
351 last statement in BODY, as elisp."
355 (insert (org-babel-chomp body
))
356 (let ((ess-local-process-name
357 (process-name (get-buffer-process session
)))
358 (ess-eval-visibly-p nil
))
359 (ess-eval-buffer nil
)))
360 (let ((tmp-file (org-babel-temp-file "R-")))
361 (org-babel-comint-eval-invisibly-and-wait-for-file
363 (format org-babel-R-write-object-command
364 (if row-names-p
"TRUE" "FALSE")
366 (if row-names-p
"NA" "TRUE")
368 ".Last.value" (org-babel-process-file-name tmp-file
'noquote
)))
369 (org-babel-R-process-value-result
370 (org-babel-result-cond result-params
372 (insert-file-contents tmp-file
)
374 (org-babel-import-elisp-from-file tmp-file
'(16)))
382 (lambda (line) (when (> (length line
) 0) line
))
384 (lambda (line) ;; cleanup extra prompts left in output
386 "^\\([ ]*[>+\\.][ ]?\\)+\\([[0-9]+\\|[ ]\\)" line
)
387 (substring line
(match-end 1))
389 (org-babel-comint-with-output (session org-babel-R-eoe-output
)
390 (insert (mapconcat #'org-babel-chomp
391 (list body org-babel-R-eoe-indicator
)
393 (inferior-ess-send-input)))))) "\n"))))
395 (defun org-babel-R-process-value-result (result column-names-p
)
396 "R-specific processing of return value.
397 Insert hline if column names in output have been requested."
399 (cons (car result
) (cons 'hline
(cdr result
)))
406 ;;; ob-R.el ends here