Add :version to org-exp-blocks.el option.
[org-mode/org-kjn.git] / lisp / ob-R.el
blob49a8a85cf6df14f714f5dbe2ed1e4ee4cedf4535
1 ;;; ob-R.el --- org-babel functions for R code evaluation
3 ;; Copyright (C) 2009-2012 Free Software Foundation, Inc.
5 ;; Author: Eric Schulte
6 ;; Dan Davison
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/>.
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 (defvar ess-local-process-name)
55 (defun org-babel-edit-prep:R (info)
56 (let ((session (cdr (assoc :session (nth 2 info)))))
57 (when (and session (string-match "^\\*\\(.+?\\)\\*$" session))
58 (save-match-data (org-babel-R-initiate-session session nil))
59 (setq ess-local-process-name (match-string 1 session)))))
61 (defun org-babel-expand-body:R (body params &optional graphics-file)
62 "Expand BODY according to PARAMS, return the expanded body."
63 (let ((graphics-file
64 (or graphics-file (org-babel-R-graphical-output-file params))))
65 (mapconcat
66 #'identity
67 ((lambda (inside)
68 (if graphics-file
69 (append
70 (list (org-babel-R-construct-graphics-device-call
71 graphics-file params))
72 inside
73 (list "dev.off()"))
74 inside))
75 (append (org-babel-variable-assignments:R params)
76 (list body))) "\n")))
78 (defun org-babel-execute:R (body params)
79 "Execute a block of R code.
80 This function is called by `org-babel-execute-src-block'."
81 (save-excursion
82 (let* ((result-params (cdr (assoc :result-params params)))
83 (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 result-params
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 (:tex . "tikz")
201 (:tiff . "tiff")
202 (:png . "png")
203 (:svg . "svg")
204 (:pdf . "pdf")
205 (:ps . "postscript")
206 (:postscript . "postscript")))
207 (allowed-args '(:width :height :bg :units :pointsize
208 :antialias :quality :compression :res
209 :type :family :title :fonts :version
210 :paper :encoding :pagecentre :colormodel
211 :useDingbats :horizontal))
212 (device (and (string-match ".+\\.\\([^.]+\\)" out-file)
213 (match-string 1 out-file)))
214 (extra-args (cdr (assq :R-dev-args params))) filearg args)
215 (setq device (or (and device (cdr (assq (intern (concat ":" device))
216 devices))) "png"))
217 (setq filearg
218 (if (member device '("pdf" "postscript" "svg" "tikz")) "file" "filename"))
219 (setq args (mapconcat
220 (lambda (pair)
221 (if (member (car pair) allowed-args)
222 (format ",%s=%s"
223 (substring (symbol-name (car pair)) 1)
224 (cdr pair)) ""))
225 params ""))
226 (format "%s(%s=\"%s\"%s%s%s)"
227 device filearg out-file args
228 (if extra-args "," "") (or extra-args ""))))
230 (defvar org-babel-R-eoe-indicator "'org_babel_R_eoe'")
231 (defvar org-babel-R-eoe-output "[1] \"org_babel_R_eoe\"")
233 (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\")")
235 (defun org-babel-R-evaluate
236 (session body result-type result-params column-names-p row-names-p)
237 "Evaluate R code in BODY."
238 (if session
239 (org-babel-R-evaluate-session
240 session body result-type result-params column-names-p row-names-p)
241 (org-babel-R-evaluate-external-process
242 body result-type result-params column-names-p row-names-p)))
244 (defun org-babel-R-evaluate-external-process
245 (body result-type result-params column-names-p row-names-p)
246 "Evaluate BODY in external R process.
247 If RESULT-TYPE equals 'output then return standard output as a
248 string. If RESULT-TYPE equals 'value then return the value of the
249 last statement in BODY, as elisp."
250 (case result-type
251 (value
252 (let ((tmp-file (org-babel-temp-file "R-")))
253 (org-babel-eval org-babel-R-command
254 (format org-babel-R-write-object-command
255 (if row-names-p "TRUE" "FALSE")
256 (if column-names-p
257 (if row-names-p "NA" "TRUE")
258 "FALSE")
259 (format "{function ()\n{\n%s\n}}()" body)
260 (org-babel-process-file-name tmp-file 'noquote)))
261 (org-babel-R-process-value-result
262 (if (or (member "scalar" result-params)
263 (member "verbatim" result-params))
264 (with-temp-buffer
265 (insert-file-contents tmp-file)
266 (buffer-string))
267 (org-babel-import-elisp-from-file tmp-file '(16)))
268 column-names-p)))
269 (output (org-babel-eval org-babel-R-command body))))
271 (defun org-babel-R-evaluate-session
272 (session body result-type result-params column-names-p row-names-p)
273 "Evaluate BODY in SESSION.
274 If RESULT-TYPE equals 'output then return standard output as a
275 string. If RESULT-TYPE equals 'value then return the value of the
276 last statement in BODY, as elisp."
277 (case result-type
278 (value
279 (with-temp-buffer
280 (insert (org-babel-chomp body))
281 (let ((ess-local-process-name
282 (process-name (get-buffer-process session)))
283 (ess-eval-visibly-p nil))
284 (ess-eval-buffer nil)))
285 (let ((tmp-file (org-babel-temp-file "R-")))
286 (org-babel-comint-eval-invisibly-and-wait-for-file
287 session tmp-file
288 (format org-babel-R-write-object-command
289 (if row-names-p "TRUE" "FALSE")
290 (if column-names-p
291 (if row-names-p "NA" "TRUE")
292 "FALSE")
293 ".Last.value" (org-babel-process-file-name tmp-file 'noquote)))
294 (org-babel-R-process-value-result
295 (if (or (member "scalar" result-params)
296 (member "verbatim" result-params))
297 (with-temp-buffer
298 (insert-file-contents tmp-file)
299 (buffer-string))
300 (org-babel-import-elisp-from-file tmp-file '(16)))
301 column-names-p)))
302 (output
303 (mapconcat
304 #'org-babel-chomp
305 (butlast
306 (delq nil
307 (mapcar
308 (lambda (line) (when (> (length line) 0) line))
309 (mapcar
310 (lambda (line) ;; cleanup extra prompts left in output
311 (if (string-match
312 "^\\([ ]*[>+\\.][ ]?\\)+\\([[0-9]+\\|[ ]\\)" line)
313 (substring line (match-end 1))
314 line))
315 (org-babel-comint-with-output (session org-babel-R-eoe-output)
316 (insert (mapconcat #'org-babel-chomp
317 (list body org-babel-R-eoe-indicator)
318 "\n"))
319 (inferior-ess-send-input)))))) "\n"))))
321 (defun org-babel-R-process-value-result (result column-names-p)
322 "R-specific processing of return value.
323 Insert hline if column names in output have been requested."
324 (if column-names-p
325 (cons (car result) (cons 'hline (cdr result)))
326 result))
328 (provide 'ob-R)
332 ;;; ob-R.el ends here