ob-R.el 13 KB

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