org-babel-R.el 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. ;;; org-babel-R.el --- org-babel functions for R code evaluation
  2. ;; Copyright (C) 2009 Eric Schulte
  3. ;; Author: Eric Schulte
  4. ;; Keywords: literate programming, reproducible research, R, statistics
  5. ;; Homepage: http://orgmode.org
  6. ;; Version: 0.01
  7. ;;; License:
  8. ;; This program 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, or (at your option)
  11. ;; any later version.
  12. ;;
  13. ;; This program is distributed in the hope that it will be useful,
  14. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;; GNU General Public License for more details.
  17. ;;
  18. ;; You should have received a copy of the GNU General Public License
  19. ;; along with GNU Emacs; see the file COPYING. If not, write to the
  20. ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  21. ;; Boston, MA 02110-1301, USA.
  22. ;;; Commentary:
  23. ;; Org-Babel support for evaluating R code
  24. ;;; Code:
  25. (require 'org-babel)
  26. (org-babel-add-interpreter "R")
  27. (add-to-list 'org-babel-tangle-langs '("R" "R" "#!/usr/bin/env Rscript"))
  28. (defun org-babel-execute:R (body params)
  29. "Execute a block of R code with org-babel. This function is
  30. called by `org-babel-execute-src-block'."
  31. (message "executing R source code block...")
  32. (save-window-excursion
  33. (let* ((processed-params (org-babel-process-params params))
  34. (result-type (fourth processed-params))
  35. (session (org-babel-R-initiate-session (first processed-params)))
  36. (vars (second processed-params))
  37. (column-names-p (cdr (assoc :colnames params)))
  38. (out-file (cdr (assoc :file params)))
  39. (augmented-body
  40. (concat
  41. (if out-file (concat (org-babel-R-construct-graphics-device-call out-file params) "\n") "")
  42. (mapconcat ;; define any variables
  43. (lambda (pair) (org-babel-R-assign-elisp (car pair) (cdr pair))) vars "\n")
  44. "\n" body "\n" (if out-file "dev.off()\n" "")))
  45. (result (org-babel-R-evaluate session augmented-body result-type column-names-p)))
  46. (or out-file result))))
  47. (defun org-babel-prep-session:R (session params)
  48. "Prepare SESSION according to the header arguments specified in PARAMS."
  49. (let* ((session (org-babel-R-initiate-session session))
  50. (vars (org-babel-ref-variables params)))
  51. (mapc (lambda (pair) (org-babel-R-assign-elisp session (car pair) (cdr pair))) vars)
  52. session))
  53. (defun org-babel-load-session:R (session body params)
  54. "Load BODY into SESSION."
  55. (save-window-excursion
  56. (let ((buffer (org-babel-prep-session:R session params)))
  57. (with-current-buffer buffer
  58. (goto-char (process-mark (get-buffer-process (current-buffer))))
  59. (insert (org-babel-chomp body)))
  60. buffer)))
  61. ;; helper functions
  62. (defun org-babel-R-quote-tsv-field (s)
  63. "Quote field S for export to R."
  64. (if (stringp s)
  65. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  66. (format "%S" s)))
  67. (defun org-babel-R-assign-elisp (name value)
  68. "Read the elisp VALUE into a variable named NAME."
  69. (if (listp value)
  70. (let ((transition-file (make-temp-file "org-babel-R-import")))
  71. ;; ensure VALUE has an orgtbl structure (depth of at least 2)
  72. (unless (listp (car value)) (setq value (list value)))
  73. (with-temp-file transition-file
  74. (insert (orgtbl-to-tsv value '(:fmt org-babel-R-quote-tsv-field)))
  75. (insert "\n"))
  76. (format "%s <- read.table(\"%s\", header=%s, sep=\"\\t\", as.is=TRUE)"
  77. name transition-file (if (eq (second value) 'hline) "TRUE" "FALSE")))
  78. (format "%s <- %s" name (org-babel-R-quote-tsv-field value))))
  79. (defun org-babel-R-initiate-session (session)
  80. "If there is not a current R process then create one."
  81. (unless (string= session "none")
  82. (setq session (or session "*R*"))
  83. (if (org-babel-comint-buffer-livep session)
  84. session
  85. (save-window-excursion
  86. (R)
  87. (rename-buffer (if (bufferp session) (buffer-name session)
  88. (if (stringp session) session (buffer-name)))) (current-buffer)))))
  89. (defun org-babel-R-construct-graphics-device-call (out-file params)
  90. "Construct the call to the graphics device"
  91. (let ((devices
  92. '((:bmp . "bmp")
  93. (:jpg . "jpeg")
  94. (:jpeg . "jpeg")
  95. (:tiff . "tiff")
  96. (:png . "png")
  97. (:pdf . "pdf")
  98. (:ps . "postscript")
  99. (:postscript . "postscript")))
  100. (allowed-args '(:width :height :bg :units :pointsize
  101. :antialias :quality :compression :res :type
  102. :family :title :fonts :version :paper :encoding
  103. :pagecentre :colormodel :useDingbats :horizontal))
  104. (device (and (string-match ".+\\.\\([^.]+\\)" out-file) (match-string 1 out-file)))
  105. (extra-args (cdr (assq :R-dev-args params))) filearg args)
  106. (setq device (or (and device (cdr (assq (intern (concat ":" device)) devices))) "png"))
  107. (setq filearg (if (member device '("pdf" "postscript")) "file" "filename"))
  108. (setq args (mapconcat (lambda (pair)
  109. (if (member (car pair) allowed-args)
  110. (format ",%s=%s" (substring (symbol-name (car pair)) 1) (cdr pair)) ""))
  111. params ""))
  112. (format "%s(%s=\"%s\"%s%s%s)\n" device filearg out-file args (if extra-args "," "") (or extra-args ""))))
  113. (defvar org-babel-R-eoe-indicator "'org_babel_R_eoe'")
  114. (defvar org-babel-R-eoe-output "[1] \"org_babel_R_eoe\"")
  115. (defvar org-babel-R-wrapper-method "main <- function ()\n{\n%s\n}
  116. write.table(main(), file=\"%s\", sep=\"\\t\", na=\"nil\",row.names=FALSE, col.names=%s, quote=FALSE)")
  117. (defun org-babel-R-evaluate (session body result-type column-names-p)
  118. "Pass BODY to the R process in SESSION. If RESULT-TYPE equals
  119. 'output then return a list of the outputs of the statements in
  120. BODY, if RESULT-TYPE equals 'value then return the value of the
  121. last statement in BODY, as elisp."
  122. (if (not session)
  123. ;; external process evaluation
  124. (let ((in-tmp-file (make-temp-file "R-in-functional-results"))
  125. (out-tmp-file (make-temp-file "R-out-functional-results")))
  126. (case result-type
  127. (output
  128. (with-temp-file in-tmp-file (insert body))
  129. (shell-command-to-string (format "R --slave --no-save < '%s' > '%s'"
  130. in-tmp-file out-tmp-file))
  131. (with-temp-buffer (insert-file-contents out-tmp-file) (buffer-string)))
  132. (value
  133. (with-temp-file in-tmp-file
  134. (insert (format org-babel-R-wrapper-method
  135. body out-tmp-file (if column-names-p "TRUE" "FALSE"))))
  136. (shell-command (format "R --no-save < '%s'" in-tmp-file))
  137. (org-babel-R-process-value-result
  138. (org-babel-import-elisp-from-file out-tmp-file) column-names-p))))
  139. ;; comint session evaluation
  140. (org-babel-comint-in-buffer session
  141. (let* ((tmp-file (make-temp-file "org-babel-R"))
  142. (full-body
  143. (case result-type
  144. (value
  145. (mapconcat #'org-babel-chomp (list body
  146. (format "write.table(.Last.value, file=\"%s\", sep=\"\\t\", na=\"nil\",row.names=FALSE, col.names=%s, quote=FALSE)" tmp-file (if column-names-p "TRUE" "FALSE"))
  147. org-babel-R-eoe-indicator) "\n"))
  148. (output
  149. (mapconcat #'org-babel-chomp (list body org-babel-R-eoe-indicator) "\n"))))
  150. (raw (org-babel-comint-with-output session org-babel-R-eoe-output nil
  151. (insert full-body) (inferior-ess-send-input)))
  152. (comint-prompt-regexp
  153. (concat "^\\("
  154. inferior-ess-primary-prompt
  155. "\\|"
  156. inferior-ess-secondary-prompt
  157. "\\)*"))
  158. broke results)
  159. (case result-type
  160. (value (org-babel-R-process-value-result
  161. (org-babel-import-elisp-from-file tmp-file) column-names-p))
  162. (output
  163. (flet ((extractor
  164. (el)
  165. (if (or broke
  166. (and (string-match (regexp-quote org-babel-R-eoe-output) el)
  167. (setq broke t)))
  168. nil
  169. (if (= (length el) 0)
  170. nil
  171. (if (string-match comint-prompt-regexp el)
  172. (substring el (match-end 0))
  173. el)))))
  174. (mapconcat
  175. #'identity
  176. (delete nil (mapcar #'extractor (mapcar #'org-babel-chomp raw))) "\n"))))))))
  177. (defun org-babel-R-process-value-result (result column-names-p)
  178. "R-specific processing of return value prior to return to org-babel.
  179. Currently, insert hline if column names in output have been requested."
  180. (if column-names-p
  181. (cons (car result) (cons 'hline (cdr result)))
  182. result))
  183. (provide 'org-babel-R)
  184. ;;; org-babel-R.el ends here