ob-R.el 16 KB

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