ob-R.el 14 KB

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