Merge branch 'master' of git+ssh://repo.or.cz/srv/git/org-mode
[org-mode/org-jambu.git] / lisp / ob-R.el
blob127285babe1a79b789e251f2cf548e115545c4af
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: 0.01
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 "ob-table" (table params))
37 (declare-function R "ext:essd-r" (&optional start-args))
38 (declare-function inferior-ess-send-input "ext:ess-inf" ())
40 (defconst org-babel-header-arg-names:R
41 '(width height bg units pointsize antialias quality compression
42 res type family title fonts version paper encoding
43 pagecentre colormodel useDingbats horizontal)
44 "R-specific header arguments.")
46 (defvar org-babel-default-header-args:R '())
48 (defvar org-babel-R-command "R --slave --no-save"
49 "Name of command to use for executing R code.")
51 (defun org-babel-expand-body:R (body params &optional processed-params)
52 "Expand BODY according to PARAMS, return the expanded body."
53 (let* ((processed-params (or processed-params
54 (org-babel-process-params params)))
55 (vars (mapcar
56 (lambda (i)
57 (cons (car (nth i (nth 1 processed-params)))
58 (org-babel-reassemble-table
59 (cdr (nth i (nth 1 processed-params)))
60 (cdr (nth i (nth 4 processed-params)))
61 (cdr (nth i (nth 5 processed-params))))))
62 (number-sequence 0 (1- (length (nth 1 processed-params))))))
63 (out-file (cdr (assoc :file params))))
64 (mapconcat ;; define any variables
65 #'org-babel-trim
66 ((lambda (inside)
67 (if out-file
68 (append
69 (list (org-babel-R-construct-graphics-device-call out-file params))
70 inside
71 (list "dev.off()"))
72 inside))
73 (append
74 (mapcar
75 (lambda (pair)
76 (org-babel-R-assign-elisp
77 (car pair) (cdr pair)
78 (equal "yes" (cdr (assoc :colnames params)))
79 (equal "yes" (cdr (assoc :rownames params)))))
80 vars)
81 (list body))) "\n")))
83 (defun org-babel-execute:R (body params)
84 "Execute a block of R code.
85 This function is called by `org-babel-execute-src-block'."
86 (save-excursion
87 (let* ((processed-params (org-babel-process-params params))
88 (result-type (nth 3 processed-params))
89 (session (org-babel-R-initiate-session
90 (first processed-params) params))
91 (colnames-p (cdr (assoc :colnames params)))
92 (rownames-p (cdr (assoc :rownames params)))
93 (out-file (cdr (assoc :file params)))
94 (full-body (org-babel-expand-body:R body params processed-params))
95 (result
96 (org-babel-R-evaluate
97 session full-body result-type
98 (or (equal "yes" colnames-p)
99 (org-babel-pick-name (nth 4 processed-params) colnames-p))
100 (or (equal "yes" rownames-p)
101 (org-babel-pick-name (nth 5 processed-params) rownames-p)))))
102 (message "result is %S" result)
103 (or out-file result))))
105 (defun org-babel-prep-session:R (session params)
106 "Prepare SESSION according to the header arguments specified in PARAMS."
107 (let* ((session (org-babel-R-initiate-session session params))
108 (vars (org-babel-ref-variables params))
109 (var-lines
110 (mapcar
111 (lambda (pair) (org-babel-R-assign-elisp
112 (car pair) (cdr pair)
113 (equal (cdr (assoc :colnames params)) "yes")
114 (equal (cdr (assoc :rownames params)) "yes")))
115 vars)))
116 (org-babel-comint-in-buffer session
117 (mapc (lambda (var)
118 (end-of-line 1) (insert var) (comint-send-input nil t)
119 (org-babel-comint-wait-for-output session)) var-lines))
120 session))
122 (defun org-babel-load-session:R (session body params)
123 "Load BODY into SESSION."
124 (save-window-excursion
125 (let ((buffer (org-babel-prep-session:R session params)))
126 (with-current-buffer buffer
127 (goto-char (process-mark (get-buffer-process (current-buffer))))
128 (insert (org-babel-chomp body)))
129 buffer)))
131 ;; helper functions
133 (defun org-babel-R-quote-tsv-field (s)
134 "Quote field S for export to R."
135 (if (stringp s)
136 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
137 (format "%S" s)))
139 (defun org-babel-R-assign-elisp (name value colnames-p rownames-p)
140 "Construct R code assigning the elisp VALUE to a variable named NAME."
141 (if (listp value)
142 (let ((transition-file (make-temp-file "org-babel-R-import")))
143 ;; ensure VALUE has an orgtbl structure (depth of at least 2)
144 (unless (listp (car value)) (setq value (list value)))
145 (with-temp-file (org-babel-maybe-remote-file transition-file)
146 (insert (orgtbl-to-tsv value '(:fmt org-babel-R-quote-tsv-field)))
147 (insert "\n"))
148 (format "%s <- read.table(\"%s\", header=%s, row.names=%s, sep=\"\\t\", as.is=TRUE)"
149 name transition-file
150 (if (or (eq (nth 1 value) 'hline) colnames-p) "TRUE" "FALSE")
151 (if rownames-p "1" "NULL")))
152 (format "%s <- %s" name (org-babel-R-quote-tsv-field value))))
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 (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 (defun org-babel-R-construct-graphics-device-call (out-file params)
172 "Construct the call to the graphics device."
173 (let ((devices
174 '((:bmp . "bmp")
175 (:jpg . "jpeg")
176 (:jpeg . "jpeg")
177 (:tiff . "tiff")
178 (:png . "png")
179 (:svg . "svg")
180 (:pdf . "pdf")
181 (:ps . "postscript")
182 (:postscript . "postscript")))
183 (allowed-args '(:width :height :bg :units :pointsize
184 :antialias :quality :compression :res
185 :type :family :title :fonts :version
186 :paper :encoding :pagecentre :colormodel
187 :useDingbats :horizontal))
188 (device (and (string-match ".+\\.\\([^.]+\\)" out-file)
189 (match-string 1 out-file)))
190 (extra-args (cdr (assq :R-dev-args params))) filearg args)
191 (setq device (or (and device (cdr (assq (intern (concat ":" device))
192 devices))) "png"))
193 (setq filearg
194 (if (member device '("pdf" "postscript" "svg")) "file" "filename"))
195 (setq args (mapconcat
196 (lambda (pair)
197 (if (member (car pair) allowed-args)
198 (format ",%s=%s"
199 (substring (symbol-name (car pair)) 1)
200 (cdr pair)) ""))
201 params ""))
202 (format "%s(%s=\"%s\"%s%s%s)"
203 device filearg out-file args
204 (if extra-args "," "") (or extra-args ""))))
206 (defvar org-babel-R-eoe-indicator "'org_babel_R_eoe'")
207 (defvar org-babel-R-eoe-output "[1] \"org_babel_R_eoe\"")
208 (defvar org-babel-R-wrapper-method "main <- function ()\n{\n%s\n}
209 write.table(main(), file=\"%s\", sep=\"\\t\", na=\"nil\",row.names=%s, col.names=%s, quote=FALSE)")
210 (defvar org-babel-R-wrapper-lastvar "write.table(.Last.value, file=\"%s\", sep=\"\\t\", na=\"nil\",row.names=%s, col.names=%s, quote=FALSE)")
212 (defun org-babel-R-evaluate
213 (session body result-type column-names-p row-names-p)
214 "Pass BODY to the R process in SESSION.
215 If RESULT-TYPE equals 'output then return a list of the outputs
216 of the statements in BODY, if RESULT-TYPE equals 'value then
217 return the value of the last statement in BODY, as elisp."
218 (if (not session)
219 ;; external process evaluation
220 (case result-type
221 (output (org-babel-eval org-babel-R-command body))
222 (value
223 (let ((tmp-file (make-temp-file "org-babel-R-results-")))
224 (org-babel-eval org-babel-R-command
225 (format org-babel-R-wrapper-method
226 body tmp-file
227 (if row-names-p "TRUE" "FALSE")
228 (if column-names-p
229 (if row-names-p "NA" "TRUE")
230 "FALSE")))
231 (org-babel-R-process-value-result
232 (org-babel-import-elisp-from-file
233 (org-babel-maybe-remote-file tmp-file)) column-names-p))))
234 ;; comint session evaluation
235 (case result-type
236 (value
237 (let ((tmp-file (make-temp-file "org-babel-R"))
238 broke)
239 (org-babel-comint-with-output (session org-babel-R-eoe-output)
240 (insert (mapconcat
241 #'org-babel-chomp
242 (list
243 body
244 (format org-babel-R-wrapper-lastvar
245 tmp-file
246 (if row-names-p "TRUE" "FALSE")
247 (if column-names-p
248 (if row-names-p "NA" "TRUE")
249 "FALSE"))
250 org-babel-R-eoe-indicator) "\n"))
251 (inferior-ess-send-input))
252 (org-babel-R-process-value-result
253 (org-babel-import-elisp-from-file
254 (org-babel-maybe-remote-file tmp-file)) column-names-p)))
255 (output
256 (mapconcat
257 #'org-babel-chomp
258 (butlast
259 (delq nil
260 (mapcar
261 #'identity
262 (org-babel-comint-with-output (session org-babel-R-eoe-output)
263 (insert (mapconcat #'org-babel-chomp
264 (list body org-babel-R-eoe-indicator)
265 "\n"))
266 (inferior-ess-send-input)))) 2) "\n")))))
268 (defun org-babel-R-process-value-result (result column-names-p)
269 "R-specific processing of return value.
270 Insert hline if column names in output have been requested."
271 (if column-names-p
272 (cons (car result) (cons 'hline (cdr result)))
273 result))
275 (provide 'ob-R)
277 ;; arch-tag: cd4c7298-503b-450f-a3c2-f3e74b630237
279 ;;; ob-R.el ends here