ob-R.el 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. ;;; ob-R.el --- org-babel functions for R code evaluation
  2. ;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
  3. ;; Author: Eric Schulte, Dan Davison
  4. ;; Keywords: literate programming, reproducible research, R, statistics
  5. ;; Homepage: http://orgmode.org
  6. ;; Version: 0.01
  7. ;; This file is part of GNU Emacs.
  8. ;; GNU Emacs is free software: you can redistribute it and/or modify
  9. ;; it under the terms of the GNU General Public License as published by
  10. ;; the Free Software Foundation, either version 3 of the License, or
  11. ;; (at your option) any later version.
  12. ;; GNU Emacs is distributed in the hope that it will be useful,
  13. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;; GNU General Public License for more details.
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  18. ;;; Commentary:
  19. ;; Org-Babel support for evaluating R code
  20. ;;; Code:
  21. (require 'ob)
  22. (require 'ob-ref)
  23. (eval-when-compile (require 'cl))
  24. (declare-function org-babel-comint-in-buffer "ob-comint" (buffer &rest body))
  25. (declare-function comint-send-input "ob-comint" (el'.))
  26. (declare-function org-babel-comint-wait-for-output "ob-comint" (buffer))
  27. (declare-function org-babel-comint-buffer-livep "ob-comint" (buffer))
  28. (declare-function org-babel-comint-with-output "ob-comint" (meta &rest body))
  29. (declare-function orgtbl-to-tsv "ob-table" (table params))
  30. (declare-function R "ext:essd-r" (&optional start-args))
  31. (declare-function inferior-ess-send-input "ext:ess-inf" ())
  32. (defconst org-babel-header-arg-names:R
  33. '(width height bg units pointsize antialias quality compression
  34. res type family title fonts version paper encoding
  35. pagecentre colormodel useDingbats horizontal)
  36. "R-specific header arguments.")
  37. (defvar org-babel-default-header-args:R '())
  38. (defun org-babel-expand-body:R (body params &optional processed-params)
  39. "Expand BODY according to PARAMS, return the expanded body."
  40. (let* ((processed-params (or processed-params
  41. (org-babel-process-params params)))
  42. (vars (mapcar (lambda (i) (cons (car (nth i (nth 1 processed-params)))
  43. (org-babel-reassemble-table
  44. (cdr (nth i (nth 1 processed-params)))
  45. (cdr (nth i (nth 4 processed-params)))
  46. (cdr (nth i (nth 5 processed-params))))))
  47. (number-sequence 0 (1- (length (nth 1 processed-params))))))
  48. (out-file (cdr (assoc :file params))))
  49. (concat
  50. (if out-file (concat (org-babel-R-construct-graphics-device-call out-file params) "\n") "")
  51. (mapconcat ;; define any variables
  52. (lambda (pair)
  53. (org-babel-R-assign-elisp (car pair) (cdr pair)
  54. (equal "yes" (cdr (assoc :colnames params)))
  55. (equal "yes" (cdr (assoc :rownames params)))))
  56. vars "\n")
  57. "\n" body "\n" (if out-file "dev.off()\n" ""))))
  58. (defun org-babel-execute:R (body params)
  59. "Execute a block of R code with org-babel. This function is
  60. called by `org-babel-execute-src-block'."
  61. (message "executing R source code block...")
  62. (save-excursion
  63. (let* ((processed-params (org-babel-process-params params))
  64. (result-type (nth 3 processed-params))
  65. (session (org-babel-R-initiate-session (first processed-params) params))
  66. (colnames-p (cdr (assoc :colnames params)))
  67. (rownames-p (cdr (assoc :rownames params)))
  68. (out-file (cdr (assoc :file params)))
  69. (full-body (org-babel-expand-body:R body params processed-params))
  70. (result
  71. (org-babel-R-evaluate
  72. session full-body result-type
  73. (or (equal "yes" colnames-p)
  74. (org-babel-pick-name (nth 4 processed-params) colnames-p))
  75. (or (equal "yes" rownames-p)
  76. (org-babel-pick-name (nth 5 processed-params) rownames-p)))))
  77. (or out-file result))))
  78. (defun org-babel-prep-session:R (session params)
  79. "Prepare SESSION according to the header arguments specified in PARAMS."
  80. (let* ((session (org-babel-R-initiate-session session params))
  81. (vars (org-babel-ref-variables params))
  82. (var-lines
  83. (mapcar
  84. (lambda (pair) (org-babel-R-assign-elisp
  85. (car pair) (cdr pair)
  86. (equal (cdr (assoc :colnames params)) "yes")
  87. (equal (cdr (assoc :rownames params)) "yes")))
  88. vars)))
  89. (org-babel-comint-in-buffer session
  90. (mapc (lambda (var)
  91. (end-of-line 1) (insert var) (comint-send-input nil t)
  92. (org-babel-comint-wait-for-output session)) var-lines))
  93. session))
  94. (defun org-babel-load-session:R (session body params)
  95. "Load BODY into SESSION."
  96. (save-window-excursion
  97. (let ((buffer (org-babel-prep-session:R session params)))
  98. (with-current-buffer buffer
  99. (goto-char (process-mark (get-buffer-process (current-buffer))))
  100. (insert (org-babel-chomp body)))
  101. buffer)))
  102. ;; helper functions
  103. (defun org-babel-R-quote-tsv-field (s)
  104. "Quote field S for export to R."
  105. (if (stringp s)
  106. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  107. (format "%S" s)))
  108. (defun org-babel-R-assign-elisp (name value colnames-p rownames-p)
  109. "Construct R code assigning the elisp VALUE to a variable named NAME."
  110. (if (listp value)
  111. (let ((transition-file (make-temp-file "org-babel-R-import")))
  112. ;; ensure VALUE has an orgtbl structure (depth of at least 2)
  113. (unless (listp (car value)) (setq value (list value)))
  114. (with-temp-file (org-babel-maybe-remote-file transition-file)
  115. (insert (orgtbl-to-tsv value '(:fmt org-babel-R-quote-tsv-field)))
  116. (insert "\n"))
  117. (format "%s <- read.table(\"%s\", header=%s, row.names=%s, sep=\"\\t\", as.is=TRUE)"
  118. name transition-file
  119. (if (or (eq (nth 1 value) 'hline) colnames-p) "TRUE" "FALSE")
  120. (if rownames-p "1" "NULL")))
  121. (format "%s <- %s" name (org-babel-R-quote-tsv-field value))))
  122. (defun org-babel-R-initiate-session (session params)
  123. "If there is not a current R process then create one."
  124. (unless (string= session "none")
  125. (let ((session (or session "*R*"))
  126. (ess-ask-for-ess-directory (not (cdr (assoc :dir params)))))
  127. (if (org-babel-comint-buffer-livep session)
  128. session
  129. (save-window-excursion
  130. (R)
  131. (rename-buffer (if (bufferp session) (buffer-name session)
  132. (if (stringp session) session (buffer-name)))) (current-buffer))))))
  133. (defun org-babel-R-construct-graphics-device-call (out-file params)
  134. "Construct the call to the graphics device."
  135. (let ((devices
  136. '((:bmp . "bmp")
  137. (:jpg . "jpeg")
  138. (:jpeg . "jpeg")
  139. (:tiff . "tiff")
  140. (:png . "png")
  141. (:svg . "svg")
  142. (:pdf . "pdf")
  143. (:ps . "postscript")
  144. (:postscript . "postscript")))
  145. (allowed-args '(:width :height :bg :units :pointsize
  146. :antialias :quality :compression :res :type
  147. :family :title :fonts :version :paper :encoding
  148. :pagecentre :colormodel :useDingbats :horizontal))
  149. (device (and (string-match ".+\\.\\([^.]+\\)" out-file) (match-string 1 out-file)))
  150. (extra-args (cdr (assq :R-dev-args params))) filearg args)
  151. (setq device (or (and device (cdr (assq (intern (concat ":" device)) devices))) "png"))
  152. (setq filearg (if (member device '("pdf" "postscript" "svg")) "file" "filename"))
  153. (setq args (mapconcat (lambda (pair)
  154. (if (member (car pair) allowed-args)
  155. (format ",%s=%s" (substring (symbol-name (car pair)) 1) (cdr pair)) ""))
  156. params ""))
  157. (format "%s(%s=\"%s\"%s%s%s)\n" device filearg out-file args (if extra-args "," "") (or extra-args ""))))
  158. (defvar org-babel-R-eoe-indicator "'org_babel_R_eoe'")
  159. (defvar org-babel-R-eoe-output "[1] \"org_babel_R_eoe\"")
  160. (defvar org-babel-R-wrapper-method "main <- function ()\n{\n%s\n}
  161. write.table(main(), file=\"%s\", sep=\"\\t\", na=\"nil\",row.names=%s, col.names=%s, quote=FALSE)")
  162. (defvar inferior-ess-primary-prompt)
  163. (defvar inferior-ess-secondary-prompt)
  164. (defun org-babel-R-evaluate (session body result-type column-names-p row-names-p)
  165. "Pass BODY to the R process in SESSION. If RESULT-TYPE equals
  166. 'output then return a list of the outputs of the statements in
  167. BODY, if RESULT-TYPE equals 'value then return the value of the
  168. last statement in BODY, as elisp."
  169. (if (not session)
  170. ;; external process evaluation
  171. (case result-type
  172. (output
  173. (with-temp-buffer
  174. (insert body)
  175. (org-babel-shell-command-on-region (point-min) (point-max) "R --slave --no-save" 'current-buffer 'replace)
  176. (org-babel-trim (buffer-string))))
  177. (value
  178. (let* ((tmp-file (make-temp-file "R-out-functional-results")) exit-code
  179. (stderr
  180. (with-temp-buffer
  181. (insert (format org-babel-R-wrapper-method
  182. body tmp-file (if row-names-p "TRUE" "FALSE") (if column-names-p (if row-names-p "NA" "TRUE") "FALSE")))
  183. (setq exit-code (org-babel-shell-command-on-region
  184. (point-min) (point-max) "R --no-save" nil 'replace (current-buffer)))
  185. (buffer-string))))
  186. (if (> exit-code 0) (org-babel-error-notify exit-code stderr))
  187. (org-babel-R-process-value-result
  188. (org-babel-import-elisp-from-file (org-babel-maybe-remote-file tmp-file))
  189. column-names-p))))
  190. ;; comint session evaluation
  191. (org-babel-comint-in-buffer session
  192. (let* ((tmp-file (make-temp-file "org-babel-R"))
  193. (full-body
  194. (case result-type
  195. (value
  196. (mapconcat #'org-babel-chomp (list body
  197. (format "write.table(.Last.value, file=\"%s\", sep=\"\\t\", na=\"nil\",row.names=%s, col.names=%s, quote=FALSE)" tmp-file (if row-names-p "TRUE" "FALSE") (if column-names-p (if row-names-p "NA" "TRUE") "FALSE"))
  198. org-babel-R-eoe-indicator) "\n"))
  199. (output
  200. (mapconcat #'org-babel-chomp (list body org-babel-R-eoe-indicator) "\n"))))
  201. (raw
  202. (org-babel-comint-with-output (session org-babel-R-eoe-output)
  203. (insert full-body) (inferior-ess-send-input)))
  204. (comint-prompt-regexp
  205. (concat "^\\("
  206. inferior-ess-primary-prompt
  207. "\\|"
  208. inferior-ess-secondary-prompt
  209. "\\)*"))
  210. broke results)
  211. (case result-type
  212. (value (org-babel-R-process-value-result
  213. (org-babel-import-elisp-from-file
  214. (org-babel-maybe-remote-file tmp-file))
  215. column-names-p))
  216. (output
  217. (flet ((extractor
  218. (el)
  219. (if (or broke
  220. (and (string-match (regexp-quote org-babel-R-eoe-output) el)
  221. (setq broke t)))
  222. nil
  223. (if (= (length el) 0)
  224. nil
  225. (if (string-match comint-prompt-regexp el)
  226. (org-babel-trim (substring el (match-end 0)))
  227. el)))))
  228. (mapconcat
  229. #'identity
  230. (delete nil (mapcar #'extractor (mapcar #'org-babel-chomp raw))) "\n"))))))))
  231. (defun org-babel-R-process-value-result (result column-names-p)
  232. "R-specific processing of return value prior to return to
  233. org-babel. Insert hline if column names in output have been
  234. requested."
  235. (if column-names-p
  236. (cons (car result) (cons 'hline (cdr result)))
  237. result))
  238. (provide 'ob-R)
  239. ;; arch-tag: cd4c7298-503b-450f-a3c2-f3e74b630237
  240. ;;; ob-R.el ends here