ob-R.el 10 KB

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