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