1 ;;; ob-R.el --- org-babel functions for R code evaluation
3 ;; Copyright (C) 2009-2013 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
))
41 (defconst org-babel-header-args
:R
62 (results .
((file list vector table scalar verbatim
)
63 (raw org html latex code pp wrap
)
64 (replace silent 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-local-process-name
) ; dynamically scoped
90 (defun org-babel-edit-prep:R
(info)
91 (let ((session (cdr (assoc :session
(nth 2 info
)))))
92 (when (and session
(string-match "^\\*\\(.+?\\)\\*$" session
))
93 (save-match-data (org-babel-R-initiate-session session nil
)))))
95 (defun org-babel-expand-body:R
(body params
&optional graphics-file
)
96 "Expand BODY according to PARAMS, return the expanded body."
98 (or graphics-file
(org-babel-R-graphical-output-file params
))))
104 (list (org-babel-R-construct-graphics-device-call
105 graphics-file params
))
110 (when (cdr (assoc :prologue params
))
111 (list (cdr (assoc :prologue params
))))
112 (org-babel-variable-assignments:R params
)
114 (when (cdr (assoc :epilogue params
))
115 (list (cdr (assoc :epilogue params
)))))) "\n")))
117 (defun org-babel-execute:R
(body params
)
118 "Execute a block of R code.
119 This function is called by `org-babel-execute-src-block'."
121 (let* ((result-params (cdr (assoc :result-params params
)))
122 (result-type (cdr (assoc :result-type params
)))
123 (session (org-babel-R-initiate-session
124 (cdr (assoc :session params
)) params
))
125 (colnames-p (cdr (assoc :colnames params
)))
126 (rownames-p (cdr (assoc :rownames params
)))
127 (graphics-file (org-babel-R-graphical-output-file params
))
128 (full-body (org-babel-expand-body:R body params graphics-file
))
130 (org-babel-R-evaluate
131 session full-body result-type result-params
132 (or (equal "yes" colnames-p
)
134 (cdr (assoc :colname-names params
)) colnames-p
))
135 (or (equal "yes" rownames-p
)
137 (cdr (assoc :rowname-names params
)) rownames-p
)))))
138 (if graphics-file nil result
))))
140 (defun org-babel-prep-session:R
(session params
)
141 "Prepare SESSION according to the header arguments specified in PARAMS."
142 (let* ((session (org-babel-R-initiate-session session params
))
143 (var-lines (org-babel-variable-assignments:R params
)))
144 (org-babel-comint-in-buffer session
146 (end-of-line 1) (insert var
) (comint-send-input nil t
)
147 (org-babel-comint-wait-for-output session
)) var-lines
))
150 (defun org-babel-load-session:R
(session body params
)
151 "Load BODY into SESSION."
152 (save-window-excursion
153 (let ((buffer (org-babel-prep-session:R session params
)))
154 (with-current-buffer buffer
155 (goto-char (process-mark (get-buffer-process (current-buffer))))
156 (insert (org-babel-chomp body
)))
161 (defun org-babel-variable-assignments:R
(params)
162 "Return list of R statements assigning the block's variables."
163 (let ((vars (mapcar #'cdr
(org-babel-get-header params
:var
))))
166 (org-babel-R-assign-elisp
167 (car pair
) (cdr pair
)
168 (equal "yes" (cdr (assoc :colnames params
)))
169 (equal "yes" (cdr (assoc :rownames params
)))))
172 (cons (car (nth i vars
))
173 (org-babel-reassemble-table
175 (cdr (nth i
(cdr (assoc :colname-names params
))))
176 (cdr (nth i
(cdr (assoc :rowname-names params
)))))))
177 (org-number-sequence 0 (1- (length vars
)))))))
179 (defun org-babel-R-quote-tsv-field (s)
180 "Quote field S for export to R."
182 (concat "\"" (mapconcat 'identity
(split-string s
"\"") "\"\"") "\"")
185 (defun org-babel-R-assign-elisp (name value colnames-p rownames-p
)
186 "Construct R code assigning the elisp VALUE to a variable named NAME."
188 (let ((max (apply #'max
(mapcar #'length
(org-remove-if-not
189 #'sequencep value
))))
190 (min (apply #'min
(mapcar #'length
(org-remove-if-not
191 #'sequencep value
))))
192 (transition-file (org-babel-temp-file "R-import-")))
193 ;; ensure VALUE has an orgtbl structure (depth of at least 2)
194 (unless (listp (car value
)) (setq value
(list value
)))
195 (with-temp-file transition-file
197 (orgtbl-to-tsv value
'(:fmt org-babel-R-quote-tsv-field
))
199 (let ((file (org-babel-process-file-name transition-file
'noquote
))
200 (header (if (or (eq (nth 1 value
) 'hline
) colnames-p
)
202 (row-names (if rownames-p
"1" "NULL")))
204 (format "%s <- read.table(\"%s\",
208 as.is=TRUE)" name file header row-names
)
209 (format "%s <- read.table(\"%s\",
215 col.names = paste(\"V\", seq_len(%d), sep =\"\"))"
216 name file header row-names max
))))
217 (format "%s <- %s" name
(org-babel-R-quote-tsv-field value
))))
219 (defvar ess-ask-for-ess-directory
) ; dynamically scoped
220 (defun org-babel-R-initiate-session (session params
)
221 "If there is not a current R process then create one."
222 (unless (string= session
"none")
223 (let ((session (or session
"*R*"))
224 (ess-ask-for-ess-directory
225 (and (and (boundp 'ess-ask-for-ess-directory
) ess-ask-for-ess-directory
)
226 (not (cdr (assoc :dir params
))))))
227 (if (org-babel-comint-buffer-livep session
)
229 (save-window-excursion
230 (when (get-buffer session
)
231 ;; Session buffer exists, but with dead process
232 (set-buffer session
))
235 (if (bufferp session
)
236 (buffer-name session
)
237 (if (stringp session
)
240 (current-buffer))))))
242 (defun org-babel-R-associate-session (session)
243 "Associate R code buffer with an R session.
244 Make SESSION be the inferior ESS process associated with the
245 current code buffer."
246 (setq ess-local-process-name
247 (process-name (get-buffer-process session
)))
248 (ess-make-buffer-current))
250 (defun org-babel-R-graphical-output-file (params)
251 "Name of file to which R should send graphical output."
252 (and (member "graphics" (cdr (assq :result-params params
)))
253 (cdr (assq :file params
))))
255 (defvar org-babel-R-graphics-devices
256 '((:bmp
"bmp" "filename")
257 (:jpg
"jpeg" "filename")
258 (:jpeg
"jpeg" "filename")
259 (:tikz
"tikz" "file")
260 (:tiff
"tiff" "filename")
261 (:png
"png" "filename")
264 (:ps
"postscript" "file")
265 (:postscript
"postscript" "file"))
266 "An alist mapping graphics file types to R functions.
268 Each member of this list is a list with three members:
269 1. the file extension of the graphics file, as an elisp :keyword
270 2. the R graphics device function to call to generate such a file
271 3. the name of the argument to this function which specifies the
272 file to write to (typically \"file\" or \"filename\")")
274 (defun org-babel-R-construct-graphics-device-call (out-file params
)
275 "Construct the call to the graphics device."
276 (let* ((allowed-args '(:width
:height
:bg
:units
:pointsize
277 :antialias
:quality
:compression
:res
278 :type
:family
:title
:fonts
:version
279 :paper
:encoding
:pagecentre
:colormodel
280 :useDingbats
:horizontal
))
281 (device (and (string-match ".+\\.\\([^.]+\\)" out-file
)
282 (match-string 1 out-file
)))
283 (device-info (or (assq (intern (concat ":" device
))
284 org-babel-R-graphics-devices
)
285 (assq :png org-babel-R-graphics-devices
)))
286 (extra-args (cdr (assq :R-dev-args params
))) filearg args
)
287 (setq device
(nth 1 device-info
))
288 (setq filearg
(nth 2 device-info
))
289 (setq args
(mapconcat
291 (if (member (car pair
) allowed-args
)
293 (substring (symbol-name (car pair
)) 1)
296 (format "%s(%s=\"%s\"%s%s%s)"
297 device filearg out-file args
298 (if extra-args
"," "") (or extra-args
""))))
300 (defvar org-babel-R-eoe-indicator
"'org_babel_R_eoe'")
301 (defvar org-babel-R-eoe-output
"[1] \"org_babel_R_eoe\"")
303 (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\")")
305 (defun org-babel-R-evaluate
306 (session body result-type result-params column-names-p row-names-p
)
307 "Evaluate R code in BODY."
309 (org-babel-R-evaluate-session
310 session body result-type result-params column-names-p row-names-p
)
311 (org-babel-R-evaluate-external-process
312 body result-type result-params column-names-p row-names-p
)))
314 (defun org-babel-R-evaluate-external-process
315 (body result-type result-params column-names-p row-names-p
)
316 "Evaluate BODY in external R process.
317 If RESULT-TYPE equals 'output then return standard output as a
318 string. If RESULT-TYPE equals 'value then return the value of the
319 last statement in BODY, as elisp."
322 (let ((tmp-file (org-babel-temp-file "R-")))
323 (org-babel-eval org-babel-R-command
324 (format org-babel-R-write-object-command
325 (if row-names-p
"TRUE" "FALSE")
327 (if row-names-p
"NA" "TRUE")
329 (format "{function ()\n{\n%s\n}}()" body
)
330 (org-babel-process-file-name tmp-file
'noquote
)))
331 (org-babel-R-process-value-result
332 (org-babel-result-cond result-params
334 (insert-file-contents tmp-file
)
336 (org-babel-import-elisp-from-file tmp-file
'(16)))
338 (output (org-babel-eval org-babel-R-command body
))))
340 (defun org-babel-R-evaluate-session
341 (session body result-type result-params column-names-p row-names-p
)
342 "Evaluate BODY in SESSION.
343 If RESULT-TYPE equals 'output then return standard output as a
344 string. If RESULT-TYPE equals 'value then return the value of the
345 last statement in BODY, as elisp."
349 (insert (org-babel-chomp body
))
350 (let ((ess-local-process-name
351 (process-name (get-buffer-process session
)))
352 (ess-eval-visibly-p nil
))
353 (ess-eval-buffer nil
)))
354 (let ((tmp-file (org-babel-temp-file "R-")))
355 (org-babel-comint-eval-invisibly-and-wait-for-file
357 (format org-babel-R-write-object-command
358 (if row-names-p
"TRUE" "FALSE")
360 (if row-names-p
"NA" "TRUE")
362 ".Last.value" (org-babel-process-file-name tmp-file
'noquote
)))
363 (org-babel-R-process-value-result
364 (org-babel-result-cond result-params
366 (insert-file-contents tmp-file
)
368 (org-babel-import-elisp-from-file tmp-file
'(16)))
376 (lambda (line) (when (> (length line
) 0) line
))
378 (lambda (line) ;; cleanup extra prompts left in output
380 "^\\([ ]*[>+\\.][ ]?\\)+\\([[0-9]+\\|[ ]\\)" line
)
381 (substring line
(match-end 1))
383 (org-babel-comint-with-output (session org-babel-R-eoe-output
)
384 (insert (mapconcat #'org-babel-chomp
385 (list body org-babel-R-eoe-indicator
)
387 (inferior-ess-send-input)))))) "\n"))))
389 (defun org-babel-R-process-value-result (result column-names-p
)
390 "R-specific processing of return value.
391 Insert hline if column names in output have been requested."
393 (cons (car result
) (cons 'hline
(cdr result
)))
400 ;;; ob-R.el ends here