ob-R.el 15 KB

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