ob-R.el 9.9 KB

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