ob-R.el 11 KB

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