org-babel-R.el 8.3 KB

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