ob-R.el 12 KB

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