ob-R.el 16 KB

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