1 ;;; ob-R.el --- org-babel functions for R code evaluation
3 ;; Copyright (C) 2009-2012 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
34 (eval-when-compile (require 'cl
))
36 (declare-function orgtbl-to-tsv
"org-table" (table params
))
37 (declare-function R
"ext:essd-r" (&optional start-args
))
38 (declare-function inferior-ess-send-input
"ext:ess-inf" ())
39 (declare-function ess-make-buffer-current
"ext:ess-inf" ())
40 (declare-function ess-eval-buffer
"ext:ess-inf" (vis))
41 (declare-function org-number-sequence
"org-compat" (from &optional to inc
))
42 (declare-function org-remove-if-not
"org" (predicate seq
))
44 (defconst org-babel-header-args
:R
65 (results .
((file list vector table scalar verbatim
)
66 (raw org html latex code pp wrap
)
67 (replace silent append prepend
)
68 (output value graphics
))))
69 "R-specific header arguments.")
71 (defvar org-babel-default-header-args
:R
'())
73 (defcustom org-babel-R-command
"R --slave --no-save"
74 "Name of command to use for executing R code."
79 (defvar ess-local-process-name
)
80 (defun org-babel-edit-prep:R
(info)
81 (let ((session (cdr (assoc :session
(nth 2 info
)))))
82 (when (and session
(string-match "^\\*\\(.+?\\)\\*$" session
))
83 (save-match-data (org-babel-R-initiate-session session nil
))
84 (setq ess-local-process-name
(match-string 1 session
)))))
86 (defun org-babel-expand-body:R
(body params
&optional graphics-file
)
87 "Expand BODY according to PARAMS, return the expanded body."
89 (or graphics-file
(org-babel-R-graphical-output-file params
))))
95 (list (org-babel-R-construct-graphics-device-call
96 graphics-file params
))
100 (append (org-babel-variable-assignments:R params
)
101 (list body
))) "\n")))
103 (defun org-babel-execute:R
(body params
)
104 "Execute a block of R code.
105 This function is called by `org-babel-execute-src-block'."
107 (let* ((result-params (cdr (assoc :result-params params
)))
108 (result-type (cdr (assoc :result-type params
)))
109 (session (org-babel-R-initiate-session
110 (cdr (assoc :session params
)) params
))
111 (colnames-p (cdr (assoc :colnames params
)))
112 (rownames-p (cdr (assoc :rownames params
)))
113 (graphics-file (org-babel-R-graphical-output-file params
))
114 (full-body (org-babel-expand-body:R body params graphics-file
))
116 (org-babel-R-evaluate
117 session full-body result-type result-params
118 (or (equal "yes" colnames-p
)
120 (cdr (assoc :colname-names params
)) colnames-p
))
121 (or (equal "yes" rownames-p
)
123 (cdr (assoc :rowname-names params
)) rownames-p
)))))
124 (if graphics-file nil result
))))
126 (defun org-babel-prep-session:R
(session params
)
127 "Prepare SESSION according to the header arguments specified in PARAMS."
128 (let* ((session (org-babel-R-initiate-session session params
))
129 (var-lines (org-babel-variable-assignments:R params
)))
130 (org-babel-comint-in-buffer session
132 (end-of-line 1) (insert var
) (comint-send-input nil t
)
133 (org-babel-comint-wait-for-output session
)) var-lines
))
136 (defun org-babel-load-session:R
(session body params
)
137 "Load BODY into SESSION."
138 (save-window-excursion
139 (let ((buffer (org-babel-prep-session:R session params
)))
140 (with-current-buffer buffer
141 (goto-char (process-mark (get-buffer-process (current-buffer))))
142 (insert (org-babel-chomp body
)))
147 (defun org-babel-variable-assignments:R
(params)
148 "Return list of R statements assigning the block's variables."
149 (let ((vars (mapcar #'cdr
(org-babel-get-header params
:var
))))
152 (org-babel-R-assign-elisp
153 (car pair
) (cdr pair
)
154 (equal "yes" (cdr (assoc :colnames params
)))
155 (equal "yes" (cdr (assoc :rownames params
)))))
158 (cons (car (nth i vars
))
159 (org-babel-reassemble-table
161 (cdr (nth i
(cdr (assoc :colname-names params
))))
162 (cdr (nth i
(cdr (assoc :rowname-names params
)))))))
163 (org-number-sequence 0 (1- (length vars
)))))))
165 (defun org-babel-R-quote-tsv-field (s)
166 "Quote field S for export to R."
168 (concat "\"" (mapconcat 'identity
(split-string s
"\"") "\"\"") "\"")
171 (defun org-babel-R-assign-elisp (name value colnames-p rownames-p
)
172 "Construct R code assigning the elisp VALUE to a variable named NAME."
174 (let ((max (apply #'max
(mapcar #'length
(org-remove-if-not
175 #'sequencep value
))))
176 (min (apply #'min
(mapcar #'length
(org-remove-if-not
177 #'sequencep value
))))
178 (transition-file (org-babel-temp-file "R-import-")))
179 ;; ensure VALUE has an orgtbl structure (depth of at least 2)
180 (unless (listp (car value
)) (setq value
(list value
)))
181 (with-temp-file transition-file
183 (orgtbl-to-tsv value
'(:fmt org-babel-R-quote-tsv-field
))
185 (let ((file (org-babel-process-file-name transition-file
'noquote
))
186 (header (if (or (eq (nth 1 value
) 'hline
) colnames-p
)
188 (row-names (if rownames-p
"1" "NULL")))
190 (format "%s <- read.table(\"%s\",
194 as.is=TRUE)" name file header row-names
)
195 (format "%s <- read.table(\"%s\",
201 col.names = paste(\"V\", seq_len(%d), sep =\"\"))"
202 name file header row-names max
))))
203 (format "%s <- %s" name
(org-babel-R-quote-tsv-field value
))))
205 (defvar ess-ask-for-ess-directory nil
)
206 (defun org-babel-R-initiate-session (session params
)
207 "If there is not a current R process then create one."
208 (unless (string= session
"none")
209 (let ((session (or session
"*R*"))
210 (ess-ask-for-ess-directory
211 (and ess-ask-for-ess-directory
(not (cdr (assoc :dir params
))))))
212 (if (org-babel-comint-buffer-livep session
)
214 (save-window-excursion
217 (if (bufferp session
)
218 (buffer-name session
)
219 (if (stringp session
)
222 (current-buffer))))))
224 (defvar ess-local-process-name nil
)
225 (defun org-babel-R-associate-session (session)
226 "Associate R code buffer with an R session.
227 Make SESSION be the inferior ESS process associated with the
228 current code buffer."
229 (setq ess-local-process-name
230 (process-name (get-buffer-process session
)))
231 (ess-make-buffer-current))
233 (defun org-babel-R-graphical-output-file (params)
234 "Name of file to which R should send graphical output."
235 (and (member "graphics" (cdr (assq :result-params params
)))
236 (cdr (assq :file params
))))
238 (defun org-babel-R-construct-graphics-device-call (out-file params
)
239 "Construct the call to the graphics device."
250 (:postscript .
"postscript")))
251 (allowed-args '(:width
:height
:bg
:units
:pointsize
252 :antialias
:quality
:compression
:res
253 :type
:family
:title
:fonts
:version
254 :paper
:encoding
:pagecentre
:colormodel
255 :useDingbats
:horizontal
))
256 (device (and (string-match ".+\\.\\([^.]+\\)" out-file
)
257 (match-string 1 out-file
)))
258 (extra-args (cdr (assq :R-dev-args params
))) filearg args
)
259 (setq device
(or (and device
(cdr (assq (intern (concat ":" device
))
262 (if (member device
'("pdf" "postscript" "svg" "tikz")) "file" "filename"))
263 (setq args
(mapconcat
265 (if (member (car pair
) allowed-args
)
267 (substring (symbol-name (car pair
)) 1)
270 (format "%s(%s=\"%s\"%s%s%s)"
271 device filearg out-file args
272 (if extra-args
"," "") (or extra-args
""))))
274 (defvar org-babel-R-eoe-indicator
"'org_babel_R_eoe'")
275 (defvar org-babel-R-eoe-output
"[1] \"org_babel_R_eoe\"")
277 (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\")")
279 (defun org-babel-R-evaluate
280 (session body result-type result-params column-names-p row-names-p
)
281 "Evaluate R code in BODY."
283 (org-babel-R-evaluate-session
284 session body result-type result-params column-names-p row-names-p
)
285 (org-babel-R-evaluate-external-process
286 body result-type result-params column-names-p row-names-p
)))
288 (defun org-babel-R-evaluate-external-process
289 (body result-type result-params column-names-p row-names-p
)
290 "Evaluate BODY in external R process.
291 If RESULT-TYPE equals 'output then return standard output as a
292 string. If RESULT-TYPE equals 'value then return the value of the
293 last statement in BODY, as elisp."
296 (let ((tmp-file (org-babel-temp-file "R-")))
297 (org-babel-eval org-babel-R-command
298 (format org-babel-R-write-object-command
299 (if row-names-p
"TRUE" "FALSE")
301 (if row-names-p
"NA" "TRUE")
303 (format "{function ()\n{\n%s\n}}()" body
)
304 (org-babel-process-file-name tmp-file
'noquote
)))
305 (org-babel-R-process-value-result
306 (if (or (member "scalar" result-params
)
307 (member "verbatim" result-params
))
309 (insert-file-contents tmp-file
)
311 (org-babel-import-elisp-from-file tmp-file
'(16)))
313 (output (org-babel-eval org-babel-R-command body
))))
315 (defun org-babel-R-evaluate-session
316 (session body result-type result-params column-names-p row-names-p
)
317 "Evaluate BODY in SESSION.
318 If RESULT-TYPE equals 'output then return standard output as a
319 string. If RESULT-TYPE equals 'value then return the value of the
320 last statement in BODY, as elisp."
324 (insert (org-babel-chomp body
))
325 (let ((ess-local-process-name
326 (process-name (get-buffer-process session
)))
327 (ess-eval-visibly-p nil
))
328 (ess-eval-buffer nil
)))
329 (let ((tmp-file (org-babel-temp-file "R-")))
330 (org-babel-comint-eval-invisibly-and-wait-for-file
332 (format org-babel-R-write-object-command
333 (if row-names-p
"TRUE" "FALSE")
335 (if row-names-p
"NA" "TRUE")
337 ".Last.value" (org-babel-process-file-name tmp-file
'noquote
)))
338 (org-babel-R-process-value-result
339 (if (or (member "scalar" result-params
)
340 (member "verbatim" result-params
))
342 (insert-file-contents tmp-file
)
344 (org-babel-import-elisp-from-file tmp-file
'(16)))
352 (lambda (line) (when (> (length line
) 0) line
))
354 (lambda (line) ;; cleanup extra prompts left in output
356 "^\\([ ]*[>+\\.][ ]?\\)+\\([[0-9]+\\|[ ]\\)" line
)
357 (substring line
(match-end 1))
359 (org-babel-comint-with-output (session org-babel-R-eoe-output
)
360 (insert (mapconcat #'org-babel-chomp
361 (list body org-babel-R-eoe-indicator
)
363 (inferior-ess-send-input)))))) "\n"))))
365 (defun org-babel-R-process-value-result (result column-names-p
)
366 "R-specific processing of return value.
367 Insert hline if column names in output have been requested."
369 (cons (car result
) (cons 'hline
(cdr result
)))
376 ;;; ob-R.el ends here