ob-R.el 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. ;;; ob-R.el --- org-babel functions for R code evaluation
  2. ;; Copyright (C) 2009-2013 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. (eval-when-compile (require 'cl))
  23. (declare-function orgtbl-to-tsv "org-table" (table params))
  24. (declare-function R "ext:essd-r" (&optional start-args))
  25. (declare-function inferior-ess-send-input "ext:ess-inf" ())
  26. (declare-function ess-make-buffer-current "ext:ess-inf" ())
  27. (declare-function ess-eval-buffer "ext:ess-inf" (vis))
  28. (declare-function org-number-sequence "org-compat" (from &optional to inc))
  29. (declare-function org-remove-if-not "org" (predicate seq))
  30. (defconst org-babel-header-args:R
  31. '((width . :any)
  32. (height . :any)
  33. (bg . :any)
  34. (units . :any)
  35. (pointsize . :any)
  36. (antialias . :any)
  37. (quality . :any)
  38. (compression . :any)
  39. (res . :any)
  40. (type . :any)
  41. (family . :any)
  42. (title . :any)
  43. (fonts . :any)
  44. (version . :any)
  45. (paper . :any)
  46. (encoding . :any)
  47. (pagecentre . :any)
  48. (colormodel . :any)
  49. (useDingbats . :any)
  50. (horizontal . :any)
  51. (results . ((file list vector table scalar verbatim)
  52. (raw org html latex code pp wrap)
  53. (replace silent append prepend)
  54. (output value graphics))))
  55. "R-specific header arguments.")
  56. (defvar org-babel-default-header-args:R '())
  57. (defcustom org-babel-R-command "R --slave --no-save"
  58. "Name of command to use for executing R code."
  59. :group 'org-babel
  60. :version "24.1"
  61. :type 'string)
  62. (defvar ess-local-process-name) ; dynamically scoped
  63. (defun org-babel-edit-prep:R (info)
  64. (let ((session (cdr (assoc :session (nth 2 info)))))
  65. (when (and session (string-match "^\\*\\(.+?\\)\\*$" session))
  66. (save-match-data (org-babel-R-initiate-session session nil)))))
  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 ((max (apply #'max (mapcar #'length (org-remove-if-not
  149. #'sequencep value))))
  150. (min (apply #'min (mapcar #'length (org-remove-if-not
  151. #'sequencep value))))
  152. (transition-file (org-babel-temp-file "R-import-")))
  153. ;; ensure VALUE has an orgtbl structure (depth of at least 2)
  154. (unless (listp (car value)) (setq value (list value)))
  155. (with-temp-file transition-file
  156. (insert
  157. (orgtbl-to-tsv value '(:fmt org-babel-R-quote-tsv-field))
  158. "\n"))
  159. (let ((file (org-babel-process-file-name transition-file 'noquote))
  160. (header (if (or (eq (nth 1 value) 'hline) colnames-p)
  161. "TRUE" "FALSE"))
  162. (row-names (if rownames-p "1" "NULL")))
  163. (if (= max min)
  164. (format "%s <- read.table(\"%s\",
  165. header=%s,
  166. row.names=%s,
  167. sep=\"\\t\",
  168. as.is=TRUE)" name file header row-names)
  169. (format "%s <- read.table(\"%s\",
  170. header=%s,
  171. row.names=%s,
  172. sep=\"\\t\",
  173. as.is=TRUE,
  174. fill=TRUE,
  175. col.names = paste(\"V\", seq_len(%d), sep =\"\"))"
  176. name file header row-names max))))
  177. (format "%s <- %s" name (org-babel-R-quote-tsv-field value))))
  178. (defvar ess-ask-for-ess-directory) ; dynamically scoped
  179. (defun org-babel-R-initiate-session (session params)
  180. "If there is not a current R process then create one."
  181. (unless (string= session "none")
  182. (let ((session (or session "*R*"))
  183. (ess-ask-for-ess-directory
  184. (and (and (boundp 'ess-ask-for-ess-directory) ess-ask-for-ess-directory)
  185. (not (cdr (assoc :dir params))))))
  186. (if (org-babel-comint-buffer-livep session)
  187. session
  188. (save-window-excursion
  189. (require 'ess) (R)
  190. (rename-buffer
  191. (if (bufferp session)
  192. (buffer-name session)
  193. (if (stringp session)
  194. session
  195. (buffer-name))))
  196. (current-buffer))))))
  197. (defun org-babel-R-associate-session (session)
  198. "Associate R code buffer with an R session.
  199. Make SESSION be the inferior ESS process associated with the
  200. current code buffer."
  201. (setq ess-local-process-name
  202. (process-name (get-buffer-process session)))
  203. (ess-make-buffer-current))
  204. (defun org-babel-R-graphical-output-file (params)
  205. "Name of file to which R should send graphical output."
  206. (and (member "graphics" (cdr (assq :result-params params)))
  207. (cdr (assq :file params))))
  208. (defun org-babel-R-construct-graphics-device-call (out-file params)
  209. "Construct the call to the graphics device."
  210. (let ((devices
  211. '((:bmp . "bmp")
  212. (:jpg . "jpeg")
  213. (:jpeg . "jpeg")
  214. (:tex . "tikz")
  215. (:tiff . "tiff")
  216. (:png . "png")
  217. (:svg . "svg")
  218. (:pdf . "pdf")
  219. (:ps . "postscript")
  220. (:postscript . "postscript")))
  221. (allowed-args '(:width :height :bg :units :pointsize
  222. :antialias :quality :compression :res
  223. :type :family :title :fonts :version
  224. :paper :encoding :pagecentre :colormodel
  225. :useDingbats :horizontal))
  226. (device (and (string-match ".+\\.\\([^.]+\\)" out-file)
  227. (match-string 1 out-file)))
  228. (extra-args (cdr (assq :R-dev-args params))) filearg args)
  229. (setq device (or (and device (cdr (assq (intern (concat ":" device))
  230. devices))) "png"))
  231. (setq filearg
  232. (if (member device '("pdf" "postscript" "svg" "tikz")) "file" "filename"))
  233. (setq args (mapconcat
  234. (lambda (pair)
  235. (if (member (car pair) allowed-args)
  236. (format ",%s=%S"
  237. (substring (symbol-name (car pair)) 1)
  238. (cdr pair)) ""))
  239. params ""))
  240. (format "%s(%s=\"%s\"%s%s%s)"
  241. device filearg out-file args
  242. (if extra-args "," "") (or extra-args ""))))
  243. (defvar org-babel-R-eoe-indicator "'org_babel_R_eoe'")
  244. (defvar org-babel-R-eoe-output "[1] \"org_babel_R_eoe\"")
  245. (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\")")
  246. (defun org-babel-R-evaluate
  247. (session body result-type result-params column-names-p row-names-p)
  248. "Evaluate R code in BODY."
  249. (if session
  250. (org-babel-R-evaluate-session
  251. session body result-type result-params column-names-p row-names-p)
  252. (org-babel-R-evaluate-external-process
  253. body result-type result-params column-names-p row-names-p)))
  254. (defun org-babel-R-evaluate-external-process
  255. (body result-type result-params column-names-p row-names-p)
  256. "Evaluate BODY in external R process.
  257. If RESULT-TYPE equals 'output then return standard output as a
  258. string. If RESULT-TYPE equals 'value then return the value of the
  259. last statement in BODY, as elisp."
  260. (case result-type
  261. (value
  262. (let ((tmp-file (org-babel-temp-file "R-")))
  263. (org-babel-eval org-babel-R-command
  264. (format org-babel-R-write-object-command
  265. (if row-names-p "TRUE" "FALSE")
  266. (if column-names-p
  267. (if row-names-p "NA" "TRUE")
  268. "FALSE")
  269. (format "{function ()\n{\n%s\n}}()" body)
  270. (org-babel-process-file-name tmp-file 'noquote)))
  271. (org-babel-R-process-value-result
  272. (org-babel-result-cond result-params
  273. (with-temp-buffer
  274. (insert-file-contents tmp-file)
  275. (buffer-string))
  276. (org-babel-import-elisp-from-file tmp-file '(16)))
  277. column-names-p)))
  278. (output (org-babel-eval org-babel-R-command body))))
  279. (defun org-babel-R-evaluate-session
  280. (session body result-type result-params column-names-p row-names-p)
  281. "Evaluate BODY in SESSION.
  282. If RESULT-TYPE equals 'output then return standard output as a
  283. string. If RESULT-TYPE equals 'value then return the value of the
  284. last statement in BODY, as elisp."
  285. (case result-type
  286. (value
  287. (with-temp-buffer
  288. (insert (org-babel-chomp body))
  289. (let ((ess-local-process-name
  290. (process-name (get-buffer-process session)))
  291. (ess-eval-visibly-p nil))
  292. (ess-eval-buffer nil)))
  293. (let ((tmp-file (org-babel-temp-file "R-")))
  294. (org-babel-comint-eval-invisibly-and-wait-for-file
  295. session tmp-file
  296. (format org-babel-R-write-object-command
  297. (if row-names-p "TRUE" "FALSE")
  298. (if column-names-p
  299. (if row-names-p "NA" "TRUE")
  300. "FALSE")
  301. ".Last.value" (org-babel-process-file-name tmp-file 'noquote)))
  302. (org-babel-R-process-value-result
  303. (org-babel-result-cond result-params
  304. (with-temp-buffer
  305. (insert-file-contents tmp-file)
  306. (buffer-string))
  307. (org-babel-import-elisp-from-file tmp-file '(16)))
  308. column-names-p)))
  309. (output
  310. (mapconcat
  311. #'org-babel-chomp
  312. (butlast
  313. (delq nil
  314. (mapcar
  315. (lambda (line) (when (> (length line) 0) line))
  316. (mapcar
  317. (lambda (line) ;; cleanup extra prompts left in output
  318. (if (string-match
  319. "^\\([ ]*[>+\\.][ ]?\\)+\\([[0-9]+\\|[ ]\\)" line)
  320. (substring line (match-end 1))
  321. line))
  322. (org-babel-comint-with-output (session org-babel-R-eoe-output)
  323. (insert (mapconcat #'org-babel-chomp
  324. (list body org-babel-R-eoe-indicator)
  325. "\n"))
  326. (inferior-ess-send-input)))))) "\n"))))
  327. (defun org-babel-R-process-value-result (result column-names-p)
  328. "R-specific processing of return value.
  329. Insert hline if column names in output have been requested."
  330. (if column-names-p
  331. (cons (car result) (cons 'hline (cdr result)))
  332. result))
  333. (provide 'ob-R)
  334. ;;; ob-R.el ends here