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