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