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 (defvar org-babel-default-header-args
:R
'())
70 (defcustom org-babel-R-command
"R --slave --no-save"
71 "Name of command to use for executing R code."
76 (defvar ess-local-process-name
) ; dynamically scoped
77 (defun org-babel-edit-prep:R
(info)
78 (let ((session (cdr (assoc :session
(nth 2 info
)))))
79 (when (and session
(string-match "^\\*\\(.+?\\)\\*$" session
))
80 (save-match-data (org-babel-R-initiate-session session nil
)))))
82 (defun org-babel-expand-body:R
(body params
&optional graphics-file
)
83 "Expand BODY according to PARAMS, return the expanded body."
85 (or graphics-file
(org-babel-R-graphical-output-file params
))))
91 (list (org-babel-R-construct-graphics-device-call
92 graphics-file params
))
97 (when (cdr (assoc :prologue params
))
98 (list (cdr (assoc :prologue params
))))
99 (org-babel-variable-assignments:R params
)
101 (when (cdr (assoc :epilogue params
))
102 (list (cdr (assoc :epilogue params
)))))) "\n")))
104 (defun org-babel-execute:R
(body params
)
105 "Execute a block of R code.
106 This function is called by `org-babel-execute-src-block'."
108 (let* ((result-params (cdr (assoc :result-params params
)))
109 (result-type (cdr (assoc :result-type params
)))
110 (session (org-babel-R-initiate-session
111 (cdr (assoc :session params
)) params
))
112 (colnames-p (cdr (assoc :colnames params
)))
113 (rownames-p (cdr (assoc :rownames params
)))
114 (graphics-file (org-babel-R-graphical-output-file params
))
115 (full-body (org-babel-expand-body:R body params graphics-file
))
117 (org-babel-R-evaluate
118 session full-body result-type result-params
119 (or (equal "yes" colnames-p
)
121 (cdr (assoc :colname-names params
)) colnames-p
))
122 (or (equal "yes" rownames-p
)
124 (cdr (assoc :rowname-names params
)) rownames-p
)))))
125 (if graphics-file nil result
))))
127 (defun org-babel-prep-session:R
(session params
)
128 "Prepare SESSION according to the header arguments specified in PARAMS."
129 (let* ((session (org-babel-R-initiate-session session params
))
130 (var-lines (org-babel-variable-assignments:R params
)))
131 (org-babel-comint-in-buffer session
133 (end-of-line 1) (insert var
) (comint-send-input nil t
)
134 (org-babel-comint-wait-for-output session
)) var-lines
))
137 (defun org-babel-load-session:R
(session body params
)
138 "Load BODY into SESSION."
139 (save-window-excursion
140 (let ((buffer (org-babel-prep-session:R session params
)))
141 (with-current-buffer buffer
142 (goto-char (process-mark (get-buffer-process (current-buffer))))
143 (insert (org-babel-chomp body
)))
148 (defun org-babel-variable-assignments:R
(params)
149 "Return list of R statements assigning the block's variables."
150 (let ((vars (mapcar #'cdr
(org-babel-get-header params
:var
))))
153 (org-babel-R-assign-elisp
154 (car pair
) (cdr pair
)
155 (equal "yes" (cdr (assoc :colnames params
)))
156 (equal "yes" (cdr (assoc :rownames params
)))))
159 (cons (car (nth i vars
))
160 (org-babel-reassemble-table
162 (cdr (nth i
(cdr (assoc :colname-names params
))))
163 (cdr (nth i
(cdr (assoc :rowname-names params
)))))))
164 (org-number-sequence 0 (1- (length vars
)))))))
166 (defun org-babel-R-quote-tsv-field (s)
167 "Quote field S for export to R."
169 (concat "\"" (mapconcat 'identity
(split-string s
"\"") "\"\"") "\"")
172 (defun org-babel-R-assign-elisp (name value colnames-p rownames-p
)
173 "Construct R code assigning the elisp VALUE to a variable named NAME."
175 (let ((max (apply #'max
(mapcar #'length
(org-remove-if-not
176 #'sequencep value
))))
177 (min (apply #'min
(mapcar #'length
(org-remove-if-not
178 #'sequencep value
))))
179 (transition-file (org-babel-temp-file "R-import-")))
180 ;; ensure VALUE has an orgtbl structure (depth of at least 2)
181 (unless (listp (car value
)) (setq value
(list value
)))
182 (with-temp-file transition-file
184 (orgtbl-to-tsv value
'(:fmt org-babel-R-quote-tsv-field
))
186 (let ((file (org-babel-process-file-name transition-file
'noquote
))
187 (header (if (or (eq (nth 1 value
) 'hline
) colnames-p
)
189 (row-names (if rownames-p
"1" "NULL")))
191 (format "%s <- read.table(\"%s\",
195 as.is=TRUE)" name file header row-names
)
196 (format "%s <- read.table(\"%s\",
202 col.names = paste(\"V\", seq_len(%d), sep =\"\"))"
203 name file header row-names max
))))
204 (format "%s <- %s" name
(org-babel-R-quote-tsv-field value
))))
206 (defvar ess-ask-for-ess-directory
) ; dynamically scoped
207 (defun org-babel-R-initiate-session (session params
)
208 "If there is not a current R process then create one."
209 (unless (string= session
"none")
210 (let ((session (or session
"*R*"))
211 (ess-ask-for-ess-directory
212 (and (and (boundp 'ess-ask-for-ess-directory
) ess-ask-for-ess-directory
)
213 (not (cdr (assoc :dir params
))))))
214 (if (org-babel-comint-buffer-livep session
)
216 (save-window-excursion
217 (when (get-buffer session
)
218 ;; Session buffer exists, but with dead process
219 (set-buffer session
))
222 (if (bufferp session
)
223 (buffer-name session
)
224 (if (stringp session
)
227 (current-buffer))))))
229 (defun org-babel-R-associate-session (session)
230 "Associate R code buffer with an R session.
231 Make SESSION be the inferior ESS process associated with the
232 current code buffer."
233 (setq ess-local-process-name
234 (process-name (get-buffer-process session
)))
235 (ess-make-buffer-current))
237 (defun org-babel-R-graphical-output-file (params)
238 "Name of file to which R should send graphical output."
239 (and (member "graphics" (cdr (assq :result-params params
)))
240 (cdr (assq :file params
))))
242 (defvar org-babel-R-graphics-devices
243 '((:bmp
"bmp" "filename")
244 (:jpg
"jpeg" "filename")
245 (:jpeg
"jpeg" "filename")
246 (:tikz
"tikz" "file")
247 (:tiff
"tiff" "filename")
248 (:png
"png" "filename")
251 (:ps
"postscript" "file")
252 (:postscript
"postscript" "file"))
253 "An alist mapping graphics file types to R functions.
255 Each member of this list is a list with three members:
256 1. the file extension of the graphics file, as an elisp :keyword
257 2. the R graphics device function to call to generate such a file
258 3. the name of the argument to this function which specifies the
259 file to write to (typically \"file\" or \"filename\")")
261 (defun org-babel-R-construct-graphics-device-call (out-file params
)
262 "Construct the call to the graphics device."
263 (let* ((allowed-args '(:width
:height
:bg
:units
:pointsize
264 :antialias
:quality
:compression
:res
265 :type
:family
:title
:fonts
:version
266 :paper
:encoding
:pagecentre
:colormodel
267 :useDingbats
:horizontal
))
268 (device (and (string-match ".+\\.\\([^.]+\\)" out-file
)
269 (match-string 1 out-file
)))
270 (device-info (or (assq (intern (concat ":" device
))
271 org-babel-R-graphics-devices
)
272 (assq :png org-babel-R-graphics-devices
)))
273 (extra-args (cdr (assq :R-dev-args params
))) filearg args
)
274 (setq device
(nth 1 device-info
))
275 (setq filearg
(nth 2 device-info
))
276 (setq args
(mapconcat
278 (if (member (car pair
) allowed-args
)
280 (substring (symbol-name (car pair
)) 1)
283 (format "%s(%s=\"%s\"%s%s%s)"
284 device filearg out-file args
285 (if extra-args
"," "") (or extra-args
""))))
287 (defvar org-babel-R-eoe-indicator
"'org_babel_R_eoe'")
288 (defvar org-babel-R-eoe-output
"[1] \"org_babel_R_eoe\"")
290 (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\")")
292 (defun org-babel-R-evaluate
293 (session body result-type result-params column-names-p row-names-p
)
294 "Evaluate R code in BODY."
296 (org-babel-R-evaluate-session
297 session body result-type result-params column-names-p row-names-p
)
298 (org-babel-R-evaluate-external-process
299 body result-type result-params column-names-p row-names-p
)))
301 (defun org-babel-R-evaluate-external-process
302 (body result-type result-params column-names-p row-names-p
)
303 "Evaluate BODY in external R process.
304 If RESULT-TYPE equals 'output then return standard output as a
305 string. If RESULT-TYPE equals 'value then return the value of the
306 last statement in BODY, as elisp."
309 (let ((tmp-file (org-babel-temp-file "R-")))
310 (org-babel-eval org-babel-R-command
311 (format org-babel-R-write-object-command
312 (if row-names-p
"TRUE" "FALSE")
314 (if row-names-p
"NA" "TRUE")
316 (format "{function ()\n{\n%s\n}}()" body
)
317 (org-babel-process-file-name tmp-file
'noquote
)))
318 (org-babel-R-process-value-result
319 (org-babel-result-cond result-params
321 (insert-file-contents tmp-file
)
323 (org-babel-import-elisp-from-file tmp-file
'(16)))
325 (output (org-babel-eval org-babel-R-command body
))))
327 (defun org-babel-R-evaluate-session
328 (session body result-type result-params column-names-p row-names-p
)
329 "Evaluate BODY in SESSION.
330 If RESULT-TYPE equals 'output then return standard output as a
331 string. If RESULT-TYPE equals 'value then return the value of the
332 last statement in BODY, as elisp."
336 (insert (org-babel-chomp body
))
337 (let ((ess-local-process-name
338 (process-name (get-buffer-process session
)))
339 (ess-eval-visibly-p nil
))
340 (ess-eval-buffer nil
)))
341 (let ((tmp-file (org-babel-temp-file "R-")))
342 (org-babel-comint-eval-invisibly-and-wait-for-file
344 (format org-babel-R-write-object-command
345 (if row-names-p
"TRUE" "FALSE")
347 (if row-names-p
"NA" "TRUE")
349 ".Last.value" (org-babel-process-file-name tmp-file
'noquote
)))
350 (org-babel-R-process-value-result
351 (org-babel-result-cond result-params
353 (insert-file-contents tmp-file
)
355 (org-babel-import-elisp-from-file tmp-file
'(16)))
363 (lambda (line) (when (> (length line
) 0) line
))
365 (lambda (line) ;; cleanup extra prompts left in output
367 "^\\([ ]*[>+\\.][ ]?\\)+\\([[0-9]+\\|[ ]\\)" line
)
368 (substring line
(match-end 1))
370 (org-babel-comint-with-output (session org-babel-R-eoe-output
)
371 (insert (mapconcat #'org-babel-chomp
372 (list body org-babel-R-eoe-indicator
)
374 (inferior-ess-send-input)))))) "\n"))))
376 (defun org-babel-R-process-value-result (result column-names-p
)
377 "R-specific processing of return value.
378 Insert hline if column names in output have been requested."
380 (cons (car result
) (cons 'hline
(cdr result
)))
387 ;;; ob-R.el ends here