ob-R.el 11 KB

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