ob-R.el 13 KB

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