org-babel-R.el 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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' via multiple-value-bind."
  31. (message "executing R source code block...")
  32. (save-window-excursion
  33. (let* ((session (org-babel-R-initiate-session session))
  34. (column-names-p (cdr (assoc :colnames params)))
  35. (out-file (cdr (assoc :file params)))
  36. (augmented-body
  37. (concat
  38. (if out-file (concat (org-babel-R-construct-graphics-device-call out-file params) "\n") "")
  39. (mapconcat ;; define any variables
  40. (lambda (pair) (org-babel-R-assign-elisp (car pair) (cdr pair))) vars "\n")
  41. "\n" body "\n" (if out-file "dev.off()\n" "")))
  42. (result (org-babel-R-evaluate session augmented-body result-type column-names-p)))
  43. (or out-file result))))
  44. (defun org-babel-prep-session:R (session params)
  45. "Prepare SESSION according to the header arguments specified in PARAMS."
  46. (let* ((session (org-babel-R-initiate-session session))
  47. (vars (org-babel-ref-variables params)))
  48. (mapc (lambda (pair) (org-babel-R-assign-elisp session (car pair) (cdr pair))) vars)))
  49. ;; helper functions
  50. (defun org-babel-R-quote-tsv-field (s)
  51. "Quote field S for export to R."
  52. (if (stringp s)
  53. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  54. (format "%S" s)))
  55. (defun org-babel-R-assign-elisp (name value)
  56. "Read the elisp VALUE into a variable named NAME."
  57. (if (listp value)
  58. (let ((transition-file (make-temp-file "org-babel-R-import")))
  59. ;; ensure VALUE has an orgtbl structure (depth of at least 2)
  60. (unless (listp (car value)) (setq value (list value)))
  61. (with-temp-file transition-file
  62. (insert (orgtbl-to-tsv value '(:fmt org-babel-R-quote-tsv-field)))
  63. (insert "\n"))
  64. (format "%s <- read.table(\"%s\", header=%s, sep=\"\\t\", as.is=TRUE)"
  65. name transition-file (if (eq (second value) 'hline) "TRUE" "FALSE")))
  66. (format "%s <- %s" name (org-babel-R-quote-tsv-field value))))
  67. (defun org-babel-R-initiate-session (session)
  68. "If there is not a current R process then create one."
  69. (unless (string= session "none")
  70. (setq session (or session "*R*"))
  71. (if (org-babel-comint-buffer-livep session)
  72. session
  73. (save-window-excursion
  74. (R)
  75. (rename-buffer (if (bufferp session) (buffer-name session)
  76. (if (stringp session) session (buffer-name)))) (current-buffer)))))
  77. (defun org-babel-R-construct-graphics-device-call (out-file params)
  78. "Construct the call to the graphics device"
  79. (let ((devices
  80. '((:bmp . "bmp")
  81. (:jpg . "jpeg")
  82. (:jpeg . "jpeg")
  83. (:tiff . "tiff")
  84. (:png . "png")
  85. (:pdf . "pdf")
  86. (:ps . "postscript")
  87. (:postscript . "postscript")))
  88. (allowed-args '(:width :height :bg :units :pointsize
  89. :antialias :quality :compression :res :type
  90. :family :title :fonts :version :paper :encoding
  91. :pagecentre :colormodel :useDingbats :horizontal))
  92. (device (and (string-match ".+\\.\\([^.]+\\)" out-file) (match-string 1 out-file)))
  93. (extra-args (cdr (assq :R-dev-args params))) filearg args)
  94. (setq device (or (and device (cdr (assq (intern (concat ":" device)) devices))) "png"))
  95. (setq filearg (if (member device '("pdf" "postscript")) "file" "filename"))
  96. (setq args (mapconcat (lambda (pair)
  97. (if (member (car pair) allowed-args)
  98. (format ",%s=%s" (substring (symbol-name (car pair)) 1) (cdr pair)) ""))
  99. params ""))
  100. (format "%s(%s=\"%s\"%s%s%s)\n" device filearg out-file args (if extra-args "," "") (or extra-args ""))))
  101. (defvar org-babel-R-eoe-indicator "'org_babel_R_eoe'")
  102. (defvar org-babel-R-eoe-output "[1] \"org_babel_R_eoe\"")
  103. (defvar org-babel-R-wrapper-method "main <- function ()\n{\n%s\n}
  104. write.table(main(), file=\"%s\", sep=\"\\t\", na=\"nil\",row.names=FALSE, col.names=%s, quote=FALSE)")
  105. (defun org-babel-R-evaluate (buffer body result-type column-names-p)
  106. "Pass BODY to the R process in BUFFER. If RESULT-TYPE equals
  107. 'output then return a list of the outputs of the statements in
  108. BODY, if RESULT-TYPE equals 'value then return the value of the
  109. last statement in BODY, as elisp."
  110. (if (not session)
  111. ;; external process evaluation
  112. (let ((in-tmp-file (make-temp-file "R-in-functional-results"))
  113. (out-tmp-file (make-temp-file "R-out-functional-results")))
  114. (case result-type
  115. (output
  116. (with-temp-file in-tmp-file (insert body))
  117. (shell-command-to-string (format "R --slave --no-save < '%s' > '%s'"
  118. in-tmp-file out-tmp-file))
  119. (with-temp-buffer (insert-file-contents out-tmp-file) (buffer-string)))
  120. (value
  121. (with-temp-file in-tmp-file
  122. (insert (format org-babel-R-wrapper-method
  123. body out-tmp-file (if column-names-p "TRUE" "FALSE"))))
  124. (shell-command (format "R --no-save < '%s'" in-tmp-file))
  125. (org-babel-R-process-value-result
  126. (org-babel-import-elisp-from-file out-tmp-file) column-names-p))))
  127. ;; comint session evaluation
  128. (org-babel-comint-in-buffer buffer
  129. (let* ((tmp-file (make-temp-file "org-babel-R"))
  130. (full-body
  131. (case result-type
  132. (value
  133. (mapconcat #'org-babel-chomp (list body
  134. (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"))
  135. org-babel-R-eoe-indicator) "\n"))
  136. (output
  137. (mapconcat #'org-babel-chomp (list body org-babel-R-eoe-indicator) "\n"))))
  138. (raw (org-babel-comint-with-output buffer org-babel-R-eoe-output nil
  139. (insert full-body) (inferior-ess-send-input)))
  140. (comint-prompt-regexp
  141. (concat "^\\("
  142. inferior-ess-primary-prompt
  143. "\\|"
  144. inferior-ess-secondary-prompt
  145. "\\)*"))
  146. broke results)
  147. (case result-type
  148. (value (org-babel-R-process-value-result
  149. (org-babel-import-elisp-from-file tmp-file) column-names-p))
  150. (output
  151. (flet ((extractor
  152. (el)
  153. (if (or broke
  154. (and (string-match (regexp-quote org-babel-R-eoe-output) el)
  155. (setq broke t)))
  156. nil
  157. (if (= (length el) 0)
  158. nil
  159. (if (string-match comint-prompt-regexp el)
  160. (substring el (match-end 0))
  161. el)))))
  162. (mapconcat
  163. #'identity
  164. (delete nil (mapcar #'extractor (mapcar #'org-babel-chomp raw))) "\n"))))))))
  165. (defun org-babel-R-process-value-result (result column-names-p)
  166. "R-specific processing of return value prior to return to org-babel.
  167. Currently, insert hline if column names in output have been requested."
  168. (if column-names-p
  169. (cons (car result) (cons 'hline (cdr result)))
  170. result))
  171. (provide 'org-babel-R)
  172. ;;; org-babel-R.el ends here