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