ob-R.el 12 KB

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