ob-R.el 12 KB

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