ob-R.el 11 KB

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