* dbusbind.c (Fdbus_register_signal): When service is not
[emacs.git] / lisp / org / ob-R.el
blob2b0e6d5e16a5f7a2cb6419162cf73dd49b8c7cad
1 ;;; ob-R.el --- org-babel functions for R code evaluation
3 ;; Copyright (C) 2009-2011 Free Software Foundation, Inc.
5 ;; Author: Eric Schulte
6 ;; Dan Davison
7 ;; Keywords: literate programming, reproducible research, R, statistics
8 ;; Homepage: http://orgmode.org
9 ;; Version: 7.7
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org-Babel support for evaluating R code
30 ;;; Code:
31 (require 'ob)
32 (require 'ob-ref)
33 (require 'ob-comint)
34 (require 'ob-eval)
35 (eval-when-compile (require 'cl))
37 (declare-function orgtbl-to-tsv "org-table" (table params))
38 (declare-function R "ext:essd-r" (&optional start-args))
39 (declare-function inferior-ess-send-input "ext:ess-inf" ())
40 (declare-function ess-make-buffer-current "ext:ess-inf" ())
41 (declare-function ess-eval-buffer "ext:ess-inf" (vis))
42 (declare-function org-number-sequence "org-compat" (from &optional to inc))
44 (defconst org-babel-header-arg-names:R
45 '(width height bg units pointsize antialias quality compression
46 res type family title fonts version paper encoding
47 pagecentre colormodel useDingbats horizontal)
48 "R-specific header arguments.")
50 (defvar org-babel-default-header-args:R '())
52 (defvar org-babel-R-command "R --slave --no-save"
53 "Name of command to use for executing R code.")
55 (defvar ess-local-process-name)
56 (defun org-babel-edit-prep:R (info)
57 (let ((session (cdr (assoc :session (nth 2 info)))))
58 (when (and session (string-match "^\\*\\(.+?\\)\\*$" session))
59 (save-match-data (org-babel-R-initiate-session session nil))
60 (setq ess-local-process-name (match-string 1 session)))))
62 (defun org-babel-expand-body:R (body params &optional graphics-file)
63 "Expand BODY according to PARAMS, return the expanded body."
64 (let ((graphics-file
65 (or graphics-file (org-babel-R-graphical-output-file params))))
66 (mapconcat
67 #'identity
68 ((lambda (inside)
69 (if graphics-file
70 (append
71 (list (org-babel-R-construct-graphics-device-call
72 graphics-file params))
73 inside
74 (list "dev.off()"))
75 inside))
76 (append (org-babel-variable-assignments:R params)
77 (list body))) "\n")))
79 (defun org-babel-execute:R (body params)
80 "Execute a block of R code.
81 This function is called by `org-babel-execute-src-block'."
82 (save-excursion
83 (let* ((result-type (cdr (assoc :result-type params)))
84 (session (org-babel-R-initiate-session
85 (cdr (assoc :session params)) params))
86 (colnames-p (cdr (assoc :colnames params)))
87 (rownames-p (cdr (assoc :rownames params)))
88 (graphics-file (org-babel-R-graphical-output-file params))
89 (full-body (org-babel-expand-body:R body params graphics-file))
90 (result
91 (org-babel-R-evaluate
92 session full-body result-type
93 (or (equal "yes" colnames-p)
94 (org-babel-pick-name
95 (cdr (assoc :colname-names params)) colnames-p))
96 (or (equal "yes" rownames-p)
97 (org-babel-pick-name
98 (cdr (assoc :rowname-names params)) rownames-p)))))
99 (if graphics-file nil result))))
101 (defun org-babel-prep-session:R (session params)
102 "Prepare SESSION according to the header arguments specified in PARAMS."
103 (let* ((session (org-babel-R-initiate-session session params))
104 (var-lines (org-babel-variable-assignments:R params)))
105 (org-babel-comint-in-buffer session
106 (mapc (lambda (var)
107 (end-of-line 1) (insert var) (comint-send-input nil t)
108 (org-babel-comint-wait-for-output session)) var-lines))
109 session))
111 (defun org-babel-load-session:R (session body params)
112 "Load BODY into SESSION."
113 (save-window-excursion
114 (let ((buffer (org-babel-prep-session:R session params)))
115 (with-current-buffer buffer
116 (goto-char (process-mark (get-buffer-process (current-buffer))))
117 (insert (org-babel-chomp body)))
118 buffer)))
120 ;; helper functions
122 (defun org-babel-variable-assignments:R (params)
123 "Return list of R statements assigning the block's variables"
124 (let ((vars (mapcar #'cdr (org-babel-get-header params :var))))
125 (mapcar
126 (lambda (pair)
127 (org-babel-R-assign-elisp
128 (car pair) (cdr pair)
129 (equal "yes" (cdr (assoc :colnames params)))
130 (equal "yes" (cdr (assoc :rownames params)))))
131 (mapcar
132 (lambda (i)
133 (cons (car (nth i vars))
134 (org-babel-reassemble-table
135 (cdr (nth i vars))
136 (cdr (nth i (cdr (assoc :colname-names params))))
137 (cdr (nth i (cdr (assoc :rowname-names params)))))))
138 (org-number-sequence 0 (1- (length vars)))))))
140 (defun org-babel-R-quote-tsv-field (s)
141 "Quote field S for export to R."
142 (if (stringp s)
143 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
144 (format "%S" s)))
146 (defun org-babel-R-assign-elisp (name value colnames-p rownames-p)
147 "Construct R code assigning the elisp VALUE to a variable named NAME."
148 (if (listp value)
149 (let ((transition-file (org-babel-temp-file "R-import-")))
150 ;; ensure VALUE has an orgtbl structure (depth of at least 2)
151 (unless (listp (car value)) (setq value (list value)))
152 (with-temp-file transition-file
153 (insert (orgtbl-to-tsv value '(:fmt org-babel-R-quote-tsv-field)))
154 (insert "\n"))
155 (format "%s <- read.table(\"%s\", header=%s, row.names=%s, sep=\"\\t\", as.is=TRUE)"
156 name (org-babel-process-file-name transition-file 'noquote)
157 (if (or (eq (nth 1 value) 'hline) colnames-p) "TRUE" "FALSE")
158 (if rownames-p "1" "NULL")))
159 (format "%s <- %s" name (org-babel-R-quote-tsv-field value))))
161 (defvar ess-ask-for-ess-directory nil)
162 (defun org-babel-R-initiate-session (session params)
163 "If there is not a current R process then create one."
164 (unless (string= session "none")
165 (let ((session (or session "*R*"))
166 (ess-ask-for-ess-directory
167 (and ess-ask-for-ess-directory (not (cdr (assoc :dir params))))))
168 (if (org-babel-comint-buffer-livep session)
169 session
170 (save-window-excursion
171 (require 'ess) (R)
172 (rename-buffer
173 (if (bufferp session)
174 (buffer-name session)
175 (if (stringp session)
176 session
177 (buffer-name))))
178 (current-buffer))))))
180 (defvar ess-local-process-name nil)
181 (defun org-babel-R-associate-session (session)
182 "Associate R code buffer with an R session.
183 Make SESSION be the inferior ESS process associated with the
184 current code buffer."
185 (setq ess-local-process-name
186 (process-name (get-buffer-process session)))
187 (ess-make-buffer-current))
189 (defun org-babel-R-graphical-output-file (params)
190 "Name of file to which R should send graphical output."
191 (and (member "graphics" (cdr (assq :result-params params)))
192 (cdr (assq :file params))))
194 (defun org-babel-R-construct-graphics-device-call (out-file params)
195 "Construct the call to the graphics device."
196 (let ((devices
197 '((:bmp . "bmp")
198 (:jpg . "jpeg")
199 (:jpeg . "jpeg")
200 (:tiff . "tiff")
201 (:png . "png")
202 (:svg . "svg")
203 (:pdf . "pdf")
204 (:ps . "postscript")
205 (:postscript . "postscript")))
206 (allowed-args '(:width :height :bg :units :pointsize
207 :antialias :quality :compression :res
208 :type :family :title :fonts :version
209 :paper :encoding :pagecentre :colormodel
210 :useDingbats :horizontal))
211 (device (and (string-match ".+\\.\\([^.]+\\)" out-file)
212 (match-string 1 out-file)))
213 (extra-args (cdr (assq :R-dev-args params))) filearg args)
214 (setq device (or (and device (cdr (assq (intern (concat ":" device))
215 devices))) "png"))
216 (setq filearg
217 (if (member device '("pdf" "postscript" "svg")) "file" "filename"))
218 (setq args (mapconcat
219 (lambda (pair)
220 (if (member (car pair) allowed-args)
221 (format ",%s=%s"
222 (substring (symbol-name (car pair)) 1)
223 (cdr pair)) ""))
224 params ""))
225 (format "%s(%s=\"%s\"%s%s%s)"
226 device filearg out-file args
227 (if extra-args "," "") (or extra-args ""))))
229 (defvar org-babel-R-eoe-indicator "'org_babel_R_eoe'")
230 (defvar org-babel-R-eoe-output "[1] \"org_babel_R_eoe\"")
232 (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\")")
234 (defun org-babel-R-evaluate
235 (session body result-type column-names-p row-names-p)
236 "Evaluate R code in BODY."
237 (if session
238 (org-babel-R-evaluate-session
239 session body result-type column-names-p row-names-p)
240 (org-babel-R-evaluate-external-process
241 body result-type column-names-p row-names-p)))
243 (defun org-babel-R-evaluate-external-process
244 (body result-type column-names-p row-names-p)
245 "Evaluate BODY in external R process.
246 If RESULT-TYPE equals 'output then return standard output as a
247 string. If RESULT-TYPE equals 'value then return the value of the
248 last statement in BODY, as elisp."
249 (case result-type
250 (value
251 (let ((tmp-file (org-babel-temp-file "R-")))
252 (org-babel-eval org-babel-R-command
253 (format org-babel-R-write-object-command
254 (if row-names-p "TRUE" "FALSE")
255 (if column-names-p
256 (if row-names-p "NA" "TRUE")
257 "FALSE")
258 (format "{function ()\n{\n%s\n}}()" body)
259 (org-babel-process-file-name tmp-file 'noquote)))
260 (org-babel-R-process-value-result
261 (org-babel-import-elisp-from-file tmp-file '(16)) column-names-p)))
262 (output (org-babel-eval org-babel-R-command body))))
264 (defun org-babel-R-evaluate-session
265 (session body result-type column-names-p row-names-p)
266 "Evaluate BODY in SESSION.
267 If RESULT-TYPE equals 'output then return standard output as a
268 string. If RESULT-TYPE equals 'value then return the value of the
269 last statement in BODY, as elisp."
270 (case result-type
271 (value
272 (with-temp-buffer
273 (insert (org-babel-chomp body))
274 (let ((ess-local-process-name
275 (process-name (get-buffer-process session))))
276 (ess-eval-buffer nil)))
277 (let ((tmp-file (org-babel-temp-file "R-")))
278 (org-babel-comint-eval-invisibly-and-wait-for-file
279 session tmp-file
280 (format org-babel-R-write-object-command
281 (if row-names-p "TRUE" "FALSE")
282 (if column-names-p
283 (if row-names-p "NA" "TRUE")
284 "FALSE")
285 ".Last.value" (org-babel-process-file-name tmp-file 'noquote)))
286 (org-babel-R-process-value-result
287 (org-babel-import-elisp-from-file tmp-file '(16)) column-names-p)))
288 (output
289 (mapconcat
290 #'org-babel-chomp
291 (butlast
292 (delq nil
293 (mapcar
294 (lambda (line) (when (> (length line) 0) line))
295 (mapcar
296 (lambda (line) ;; cleanup extra prompts left in output
297 (if (string-match
298 "^\\([ ]*[>+][ ]?\\)+\\([[0-9]+\\|[ ]\\)" line)
299 (substring line (match-end 1))
300 line))
301 (org-babel-comint-with-output (session org-babel-R-eoe-output)
302 (insert (mapconcat #'org-babel-chomp
303 (list body org-babel-R-eoe-indicator)
304 "\n"))
305 (inferior-ess-send-input)))))) "\n"))))
307 (defun org-babel-R-process-value-result (result column-names-p)
308 "R-specific processing of return value.
309 Insert hline if column names in output have been requested."
310 (if column-names-p
311 (cons (car result) (cons 'hline (cdr result)))
312 result))
314 (provide 'ob-R)
318 ;;; ob-R.el ends here