ob-R.el 10 KB

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