Release 7.3
[org-mode/org-mode-NeilSmithlineMods.git] / lisp / ob-R.el
blob2be79926a44669270ae7e2ee81bf4e31bcfb13a7
1 ;;; ob-R.el --- org-babel functions for R code evaluation
3 ;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
5 ;; Author: Eric Schulte, Dan Davison
6 ;; Keywords: literate programming, reproducible research, R, statistics
7 ;; Homepage: http://orgmode.org
8 ;; Version: 7.3
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/>.
25 ;;; Commentary:
27 ;; Org-Babel support for evaluating R code
29 ;;; Code:
30 (require 'ob)
31 (require 'ob-ref)
32 (require 'ob-comint)
33 (require 'ob-eval)
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))
43 (defconst org-babel-header-arg-names:R
44 '(width height bg units pointsize antialias quality compression
45 res type family title fonts version paper encoding
46 pagecentre colormodel useDingbats horizontal)
47 "R-specific header arguments.")
49 (defvar org-babel-default-header-args:R '())
51 (defvar org-babel-R-command "R --slave --no-save"
52 "Name of command to use for executing R code.")
54 (defun org-babel-expand-body:R (body params)
55 "Expand BODY according to PARAMS, return the expanded body."
56 (let ((out-file (cdr (assoc :file params))))
57 (mapconcat
58 #'identity
59 ((lambda (inside)
60 (if out-file
61 (append
62 (list (org-babel-R-construct-graphics-device-call out-file params))
63 inside
64 (list "dev.off()"))
65 inside))
66 (append (org-babel-variable-assignments:R params)
67 (list body))) "\n")))
69 (defun org-babel-execute:R (body params)
70 "Execute a block of R code.
71 This function is called by `org-babel-execute-src-block'."
72 (save-excursion
73 (let* ((result-type (cdr (assoc :result-type params)))
74 (session (org-babel-R-initiate-session
75 (cdr (assoc :session params)) params))
76 (colnames-p (cdr (assoc :colnames params)))
77 (rownames-p (cdr (assoc :rownames params)))
78 (out-file (cdr (assoc :file params)))
79 (full-body (org-babel-expand-body:R body params))
80 (result
81 (org-babel-R-evaluate
82 session full-body result-type
83 (or (equal "yes" colnames-p)
84 (org-babel-pick-name
85 (cdr (assoc :colname-names params)) colnames-p))
86 (or (equal "yes" rownames-p)
87 (org-babel-pick-name
88 (cdr (assoc :rowname-names params)) rownames-p)))))
89 (message "result is %S" result)
90 (or out-file result))))
92 (defun org-babel-prep-session:R (session params)
93 "Prepare SESSION according to the header arguments specified in PARAMS."
94 (let* ((session (org-babel-R-initiate-session session params))
95 (var-lines (org-babel-variable-assignments:R params)))
96 (org-babel-comint-in-buffer session
97 (mapc (lambda (var)
98 (end-of-line 1) (insert var) (comint-send-input nil t)
99 (org-babel-comint-wait-for-output session)) var-lines))
100 session))
102 (defun org-babel-load-session:R (session body params)
103 "Load BODY into SESSION."
104 (save-window-excursion
105 (let ((buffer (org-babel-prep-session:R session params)))
106 (with-current-buffer buffer
107 (goto-char (process-mark (get-buffer-process (current-buffer))))
108 (insert (org-babel-chomp body)))
109 buffer)))
111 ;; helper functions
113 (defun org-babel-variable-assignments:R (params)
114 "Return list of R statements assigning the block's variables"
115 (let ((vars (mapcar #'cdr (org-babel-get-header params :var))))
116 (mapcar
117 (lambda (pair)
118 (org-babel-R-assign-elisp
119 (car pair) (cdr pair)
120 (equal "yes" (cdr (assoc :colnames params)))
121 (equal "yes" (cdr (assoc :rownames params)))))
122 (mapcar
123 (lambda (i)
124 (cons (car (nth i vars))
125 (org-babel-reassemble-table
126 (cdr (nth i vars))
127 (cdr (nth i (cdr (assoc :colname-names params))))
128 (cdr (nth i (cdr (assoc :rowname-names params)))))))
129 (org-number-sequence 0 (1- (length vars)))))))
131 (defun org-babel-R-quote-tsv-field (s)
132 "Quote field S for export to R."
133 (if (stringp s)
134 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
135 (format "%S" s)))
137 (defun org-babel-R-assign-elisp (name value colnames-p rownames-p)
138 "Construct R code assigning the elisp VALUE to a variable named NAME."
139 (if (listp value)
140 (let ((transition-file (org-babel-temp-file "R-import-")))
141 ;; ensure VALUE has an orgtbl structure (depth of at least 2)
142 (unless (listp (car value)) (setq value (list value)))
143 (with-temp-file transition-file
144 (insert (orgtbl-to-tsv value '(:fmt org-babel-R-quote-tsv-field)))
145 (insert "\n"))
146 (format "%s <- read.table(\"%s\", header=%s, row.names=%s, sep=\"\\t\", as.is=TRUE)"
147 name (org-babel-process-file-name transition-file 'noquote)
148 (if (or (eq (nth 1 value) 'hline) colnames-p) "TRUE" "FALSE")
149 (if rownames-p "1" "NULL")))
150 (format "%s <- %s" name (org-babel-R-quote-tsv-field value))))
152 (defvar ess-ask-for-ess-directory nil)
153 (defun org-babel-R-initiate-session (session params)
154 "If there is not a current R process then create one."
155 (unless (string= session "none")
156 (let ((session (or session "*R*"))
157 (ess-ask-for-ess-directory
158 (and ess-ask-for-ess-directory (not (cdr (assoc :dir params))))))
159 (if (org-babel-comint-buffer-livep session)
160 session
161 (save-window-excursion
162 (require 'ess) (R)
163 (rename-buffer
164 (if (bufferp session)
165 (buffer-name session)
166 (if (stringp session)
167 session
168 (buffer-name))))
169 (current-buffer))))))
171 (defvar ess-local-process-name nil)
172 (defun org-babel-R-associate-session (session)
173 "Associate R code buffer with an R session.
174 Make SESSION be the inferior ESS process associated with the
175 current code buffer."
176 (setq ess-local-process-name
177 (process-name (get-buffer-process session)))
178 (ess-make-buffer-current))
180 (defun org-babel-R-construct-graphics-device-call (out-file params)
181 "Construct the call to the graphics device."
182 (let ((devices
183 '((:bmp . "bmp")
184 (:jpg . "jpeg")
185 (:jpeg . "jpeg")
186 (:tiff . "tiff")
187 (:png . "png")
188 (:svg . "svg")
189 (:pdf . "pdf")
190 (:ps . "postscript")
191 (:postscript . "postscript")))
192 (allowed-args '(:width :height :bg :units :pointsize
193 :antialias :quality :compression :res
194 :type :family :title :fonts :version
195 :paper :encoding :pagecentre :colormodel
196 :useDingbats :horizontal))
197 (device (and (string-match ".+\\.\\([^.]+\\)" out-file)
198 (match-string 1 out-file)))
199 (extra-args (cdr (assq :R-dev-args params))) filearg args)
200 (setq device (or (and device (cdr (assq (intern (concat ":" device))
201 devices))) "png"))
202 (setq filearg
203 (if (member device '("pdf" "postscript" "svg")) "file" "filename"))
204 (setq args (mapconcat
205 (lambda (pair)
206 (if (member (car pair) allowed-args)
207 (format ",%s=%s"
208 (substring (symbol-name (car pair)) 1)
209 (cdr pair)) ""))
210 params ""))
211 (format "%s(%s=\"%s\"%s%s%s)"
212 device filearg out-file args
213 (if extra-args "," "") (or extra-args ""))))
215 (defvar org-babel-R-eoe-indicator "'org_babel_R_eoe'")
216 (defvar org-babel-R-eoe-output "[1] \"org_babel_R_eoe\"")
217 (defvar org-babel-R-write-object-command "{function(object, transfer.file) {invisible(if(inherits(try(write.table(object, file=transfer.file, sep=\"\\t\", na=\"nil\",row.names=%s, col.names=%s, quote=FALSE), silent=TRUE),\"try-error\")) {if(!file.exists(transfer.file)) file.create(transfer.file)})}}(object=%s, transfer.file=\"%s\")")
219 (defun org-babel-R-evaluate
220 (session body result-type column-names-p row-names-p)
221 "Evaluate R code in BODY."
222 (if session
223 (org-babel-R-evaluate-session
224 session body result-type column-names-p row-names-p)
225 (org-babel-R-evaluate-external-process
226 body result-type column-names-p row-names-p)))
228 (defun org-babel-R-evaluate-external-process
229 (body result-type column-names-p row-names-p)
230 "Evaluate BODY in external R process.
231 If RESULT-TYPE equals 'output then return standard output as a
232 string. If RESULT-TYPE equals 'value then return the value of the
233 last statement in BODY, as elisp."
234 (case result-type
235 (value
236 (let ((tmp-file (org-babel-temp-file "R-")))
237 (org-babel-eval org-babel-R-command
238 (format org-babel-R-write-object-command
239 (if row-names-p "TRUE" "FALSE")
240 (if column-names-p
241 (if row-names-p "NA" "TRUE")
242 "FALSE")
243 (format "{function ()\n{\n%s\n}}()" body)
244 (org-babel-process-file-name tmp-file 'noquote)))
245 (org-babel-R-process-value-result
246 (org-babel-import-elisp-from-file tmp-file '(16)) column-names-p)))
247 (output (org-babel-eval org-babel-R-command body))))
249 (defun org-babel-R-evaluate-session
250 (session body result-type column-names-p row-names-p)
251 "Evaluate BODY in SESSION.
252 If RESULT-TYPE equals 'output then return standard output as a
253 string. If RESULT-TYPE equals 'value then return the value of the
254 last statement in BODY, as elisp."
255 (case result-type
256 (value
257 (with-temp-buffer
258 (insert (org-babel-chomp body))
259 (let ((ess-local-process-name
260 (process-name (get-buffer-process session))))
261 (ess-eval-buffer nil)))
262 (let ((tmp-file (org-babel-temp-file "R-")))
263 (org-babel-comint-eval-invisibly-and-wait-for-file
264 session tmp-file
265 (format org-babel-R-write-object-command
266 (if row-names-p "TRUE" "FALSE")
267 (if column-names-p
268 (if row-names-p "NA" "TRUE")
269 "FALSE")
270 ".Last.value" (org-babel-process-file-name tmp-file 'noquote)))
271 (org-babel-R-process-value-result
272 (org-babel-import-elisp-from-file tmp-file '(16)) column-names-p)))
273 (output
274 (mapconcat
275 #'org-babel-chomp
276 (butlast
277 (delq nil
278 (mapcar
279 (lambda (line) ;; cleanup extra prompts left in output
280 (if (string-match
281 "^\\([ ]*[>+][ ]?\\)+\\([[0-9]+\\|[ ]\\)" line)
282 (substring line (match-end 1))
283 line))
284 (org-babel-comint-with-output (session org-babel-R-eoe-output)
285 (insert (mapconcat #'org-babel-chomp
286 (list body org-babel-R-eoe-indicator)
287 "\n"))
288 (inferior-ess-send-input)))) 2) "\n"))))
290 (defun org-babel-R-process-value-result (result column-names-p)
291 "R-specific processing of return value.
292 Insert hline if column names in output have been requested."
293 (if column-names-p
294 (cons (car result) (cons 'hline (cdr result)))
295 result))
297 (provide 'ob-R)
299 ;; arch-tag: cd4c7298-503b-450f-a3c2-f3e74b630237
301 ;;; ob-R.el ends here