ob-R.el 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. ;;; ob-R.el --- Babel Functions for R -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2009-2022 Free Software Foundation, Inc.
  3. ;; Author: Eric Schulte
  4. ;; Dan Davison
  5. ;; Maintainer: Jeremie Juste <jeremiejuste@gmail.com>
  6. ;; Keywords: literate programming, reproducible research, R, statistics
  7. ;; URL: https://orgmode.org
  8. ;; This file is part of GNU Emacs.
  9. ;; GNU Emacs is free software: you can redistribute it and/or modify
  10. ;; it under the terms of the GNU General Public License as published by
  11. ;; the Free Software Foundation, either version 3 of the License, or
  12. ;; (at your option) any later version.
  13. ;; GNU Emacs is distributed in the hope that it will be useful,
  14. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;; GNU General Public License for more details.
  17. ;; You should have received a copy of the GNU General Public License
  18. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  19. ;;; Commentary:
  20. ;; Org-Babel support for evaluating R code
  21. ;;; Code:
  22. (require 'cl-lib)
  23. (require 'ob)
  24. (declare-function orgtbl-to-tsv "org-table" (table params))
  25. (declare-function R "ext:essd-r" (&optional start-args))
  26. (declare-function inferior-ess-send-input "ext:ess-inf" ())
  27. (declare-function ess-make-buffer-current "ext:ess-inf" ())
  28. (declare-function ess-eval-buffer "ext:ess-inf" (vis))
  29. (declare-function ess-wait-for-process "ext:ess-inf"
  30. (&optional proc sec-prompt wait force-redisplay))
  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 html latex org code pp drawer)
  54. (replace silent none 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-current-process-name) ; dynamically scoped
  75. (defvar ess-local-process-name) ; dynamically scoped
  76. (defun org-babel-edit-prep:R (info)
  77. (let ((session (cdr (assq :session (nth 2 info)))))
  78. (when (and session
  79. (string-prefix-p "*" session)
  80. (string-suffix-p "*" session))
  81. (org-babel-R-initiate-session session nil))))
  82. ;; The usage of utils::read.table() ensures that the command
  83. ;; read.table() can be found even in circumstances when the utils
  84. ;; package is not in the search path from R.
  85. (defconst ob-R-transfer-variable-table-with-header
  86. "%s <- local({
  87. con <- textConnection(
  88. %S
  89. )
  90. res <- utils::read.table(
  91. con,
  92. header = %s,
  93. row.names = %s,
  94. sep = \"\\t\",
  95. as.is = TRUE
  96. )
  97. close(con)
  98. res
  99. })"
  100. "R code used to transfer a table defined as a variable from org to R.
  101. This function is used when the table contains a header.")
  102. (defconst ob-R-transfer-variable-table-without-header
  103. "%s <- local({
  104. con <- textConnection(
  105. %S
  106. )
  107. res <- utils::read.table(
  108. con,
  109. header = %s,
  110. row.names = %s,
  111. sep = \"\\t\",
  112. as.is = TRUE,
  113. fill = TRUE,
  114. col.names = paste(\"V\", seq_len(%d), sep =\"\")
  115. )
  116. close(con)
  117. res
  118. })"
  119. "R code used to transfer a table defined as a variable from org to R.
  120. This function is used when the table does not contain a header.")
  121. (defun org-babel-expand-body:R (body params &optional _graphics-file)
  122. "Expand BODY according to PARAMS, return the expanded body."
  123. (mapconcat 'identity
  124. (append
  125. (when (cdr (assq :prologue params))
  126. (list (cdr (assq :prologue params))))
  127. (org-babel-variable-assignments:R params)
  128. (list body)
  129. (when (cdr (assq :epilogue params))
  130. (list (cdr (assq :epilogue params)))))
  131. "\n"))
  132. (defun org-babel-execute:R (body params)
  133. "Execute a block of R code.
  134. This function is called by `org-babel-execute-src-block'."
  135. (save-excursion
  136. (let* ((result-params (cdr (assq :result-params params)))
  137. (result-type (cdr (assq :result-type params)))
  138. (async (org-babel-comint-use-async params))
  139. (session (org-babel-R-initiate-session
  140. (cdr (assq :session params)) params))
  141. (graphics-file (and (member "graphics" (assq :result-params params))
  142. (org-babel-graphical-output-file params)))
  143. (colnames-p (unless graphics-file (cdr (assq :colnames params))))
  144. (rownames-p (unless graphics-file (cdr (assq :rownames params))))
  145. (full-body
  146. (let ((inside
  147. (list (org-babel-expand-body:R body params graphics-file))))
  148. (mapconcat 'identity
  149. (if graphics-file
  150. (append
  151. (list (org-babel-R-construct-graphics-device-call
  152. graphics-file params))
  153. inside
  154. (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()"))
  155. inside)
  156. "\n")))
  157. (result
  158. (org-babel-R-evaluate
  159. session full-body result-type result-params
  160. (or (equal "yes" colnames-p)
  161. (org-babel-pick-name
  162. (cdr (assq :colname-names params)) colnames-p))
  163. (or (equal "yes" rownames-p)
  164. (org-babel-pick-name
  165. (cdr (assq :rowname-names params)) rownames-p))
  166. async)))
  167. (if graphics-file nil result))))
  168. (defun org-babel-prep-session:R (session params)
  169. "Prepare SESSION according to the header arguments specified in PARAMS."
  170. (let* ((session (org-babel-R-initiate-session session params))
  171. (var-lines (org-babel-variable-assignments:R params)))
  172. (org-babel-comint-in-buffer session
  173. (mapc (lambda (var)
  174. (end-of-line 1) (insert var) (comint-send-input nil t)
  175. (org-babel-comint-wait-for-output session))
  176. var-lines))
  177. session))
  178. (defun org-babel-load-session:R (session body params)
  179. "Load BODY into SESSION."
  180. (save-window-excursion
  181. (let ((buffer (org-babel-prep-session:R session params)))
  182. (with-current-buffer buffer
  183. (goto-char (process-mark (get-buffer-process (current-buffer))))
  184. (insert (org-babel-chomp body)))
  185. buffer)))
  186. ;; helper functions
  187. (defun org-babel-variable-assignments:R (params)
  188. "Return list of R statements assigning the block's variables."
  189. (let ((vars (org-babel--get-vars params)))
  190. (mapcar
  191. (lambda (pair)
  192. (org-babel-R-assign-elisp
  193. (car pair) (cdr pair)
  194. (equal "yes" (cdr (assq :colnames params)))
  195. (equal "yes" (cdr (assq :rownames params)))))
  196. (mapcar
  197. (lambda (i)
  198. (cons (car (nth i vars))
  199. (org-babel-reassemble-table
  200. (cdr (nth i vars))
  201. (cdr (nth i (cdr (assq :colname-names params))))
  202. (cdr (nth i (cdr (assq :rowname-names params)))))))
  203. (number-sequence 0 (1- (length vars)))))))
  204. (defun org-babel-R-quote-tsv-field (s)
  205. "Quote field S for export to R."
  206. (if (stringp s)
  207. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  208. (format "%S" s)))
  209. (defun org-babel-R-assign-elisp (name value colnames-p rownames-p)
  210. "Construct R code assigning the elisp VALUE to a variable named NAME."
  211. (if (listp value)
  212. (let* ((lengths (mapcar 'length (cl-remove-if-not 'sequencep value)))
  213. (max (if lengths (apply 'max lengths) 0))
  214. (min (if lengths (apply 'min lengths) 0)))
  215. ;; Ensure VALUE has an orgtbl structure (depth of at least 2).
  216. (unless (listp (car value)) (setq value (list value)))
  217. (let ((file (orgtbl-to-tsv value '(:fmt org-babel-R-quote-tsv-field)))
  218. (header (if (or (eq (nth 1 value) 'hline) colnames-p)
  219. "TRUE" "FALSE"))
  220. (row-names (if rownames-p "1" "NULL")))
  221. (if (= max min)
  222. (format ob-R-transfer-variable-table-with-header
  223. name file header row-names)
  224. (format ob-R-transfer-variable-table-without-header
  225. name file header row-names max))))
  226. (cond ((integerp value) (format "%s <- %s" name (concat (number-to-string value) "L")))
  227. ((floatp value) (format "%s <- %s" name value))
  228. ((stringp value) (format "%s <- %S" name (org-no-properties value)))
  229. (t (format "%s <- %S" name (prin1-to-string value))))))
  230. (defvar ess-ask-for-ess-directory) ; dynamically scoped
  231. (defun org-babel-R-initiate-session (session params)
  232. "If there is not a current R process then create one."
  233. (unless (string= session "none")
  234. (let ((session (or session "*R*"))
  235. (ess-ask-for-ess-directory
  236. (and (boundp 'ess-ask-for-ess-directory)
  237. ess-ask-for-ess-directory
  238. (not (cdr (assq :dir params))))))
  239. (if (org-babel-comint-buffer-livep session)
  240. session
  241. (save-window-excursion
  242. (when (get-buffer session)
  243. ;; Session buffer exists, but with dead process
  244. (set-buffer session))
  245. (require 'ess) (R)
  246. (let ((R-proc (get-process (or ess-local-process-name
  247. ess-current-process-name))))
  248. (while (process-get R-proc 'callbacks)
  249. (ess-wait-for-process R-proc)))
  250. (rename-buffer
  251. (if (bufferp session)
  252. (buffer-name session)
  253. (if (stringp session)
  254. session
  255. (buffer-name))))
  256. (current-buffer))))))
  257. (defun org-babel-R-associate-session (session)
  258. "Associate R code buffer with an R session.
  259. Make SESSION be the inferior ESS process associated with the
  260. current code buffer."
  261. (setq ess-local-process-name
  262. (process-name (get-buffer-process session)))
  263. (ess-make-buffer-current))
  264. (defvar org-babel-R-graphics-devices
  265. '((:bmp "bmp" "filename")
  266. (:jpg "jpeg" "filename")
  267. (:jpeg "jpeg" "filename")
  268. (:tikz "tikz" "file")
  269. (:tiff "tiff" "filename")
  270. (:png "png" "filename")
  271. (:svg "svg" "file")
  272. (:pdf "pdf" "file")
  273. (:ps "postscript" "file")
  274. (:postscript "postscript" "file"))
  275. "An alist mapping graphics file types to R functions.
  276. Each member of this list is a list with three members:
  277. 1. the file extension of the graphics file, as an elisp :keyword
  278. 2. the R graphics device function to call to generate such a file
  279. 3. the name of the argument to this function which specifies the
  280. file to write to (typically \"file\" or \"filename\")")
  281. (defun org-babel-R-construct-graphics-device-call (out-file params)
  282. "Construct the call to the graphics device."
  283. (let* ((allowed-args '(:width :height :bg :units :pointsize
  284. :antialias :quality :compression :res
  285. :type :family :title :fonts :version
  286. :paper :encoding :pagecentre :colormodel
  287. :useDingbats :horizontal))
  288. (device (file-name-extension out-file))
  289. (device-info (or (assq (intern (concat ":" device))
  290. org-babel-R-graphics-devices)
  291. (assq :png org-babel-R-graphics-devices)))
  292. (extra-args (cdr (assq :R-dev-args params))) filearg args)
  293. (setq device (nth 1 device-info))
  294. (setq filearg (nth 2 device-info))
  295. (setq args (mapconcat
  296. (lambda (pair)
  297. (if (member (car pair) allowed-args)
  298. (format ",%s=%S"
  299. (substring (symbol-name (car pair)) 1)
  300. (cdr pair)) ""))
  301. params ""))
  302. (format "%s(%s=\"%s\"%s%s%s); tryCatch({"
  303. device filearg out-file args
  304. (if extra-args "," "") (or extra-args ""))))
  305. (defconst org-babel-R-eoe-indicator "'org_babel_R_eoe'")
  306. (defconst org-babel-R-eoe-output "[1] \"org_babel_R_eoe\"")
  307. (defconst org-babel-R-write-object-command "{
  308. function(object,transfer.file) {
  309. object
  310. invisible(
  311. if (
  312. inherits(
  313. try(
  314. {
  315. tfile<-tempfile()
  316. write.table(object, file=tfile, sep=\"\\t\",
  317. na=\"\",row.names=%s,col.names=%s,
  318. quote=FALSE)
  319. file.rename(tfile,transfer.file)
  320. },
  321. silent=TRUE),
  322. \"try-error\"))
  323. {
  324. if(!file.exists(transfer.file))
  325. file.create(transfer.file)
  326. }
  327. )
  328. }
  329. }(object=%s,transfer.file=\"%s\")"
  330. "Template for an R command to evaluate a block of code and write result to file.
  331. Has four %s escapes to be filled in:
  332. 1. Row names, \"TRUE\" or \"FALSE\"
  333. 2. Column names, \"TRUE\" or \"FALSE\"
  334. 3. The code to be run (must be an expression, not a statement)
  335. 4. The name of the file to write to")
  336. (defun org-babel-R-evaluate
  337. (session body result-type result-params column-names-p row-names-p async)
  338. "Evaluate R code in BODY."
  339. (if session
  340. (if async
  341. (ob-session-async-org-babel-R-evaluate-session
  342. session body result-type column-names-p row-names-p)
  343. (org-babel-R-evaluate-session
  344. session body result-type result-params column-names-p row-names-p))
  345. (org-babel-R-evaluate-external-process
  346. body result-type result-params column-names-p row-names-p)))
  347. (defun org-babel-R-evaluate-external-process
  348. (body result-type result-params column-names-p row-names-p)
  349. "Evaluate BODY in external R process.
  350. If RESULT-TYPE equals `output' then return standard output as a
  351. string. If RESULT-TYPE equals `value' then return the value of the
  352. last statement in BODY, as elisp."
  353. (cl-case result-type
  354. (value
  355. (let ((tmp-file (org-babel-temp-file "R-")))
  356. (org-babel-eval org-babel-R-command
  357. (format org-babel-R-write-object-command
  358. (if row-names-p "TRUE" "FALSE")
  359. (if column-names-p
  360. (if row-names-p "NA" "TRUE")
  361. "FALSE")
  362. (format "{function ()\n{\n%s\n}}()" body)
  363. (org-babel-process-file-name tmp-file 'noquote)))
  364. (org-babel-R-process-value-result
  365. (org-babel-result-cond result-params
  366. (with-temp-buffer
  367. (insert-file-contents tmp-file)
  368. (org-babel-chomp (buffer-string) "\n"))
  369. (org-babel-import-elisp-from-file tmp-file '(16)))
  370. column-names-p)))
  371. (output (org-babel-eval org-babel-R-command body))))
  372. (defvar ess-eval-visibly-p)
  373. (defun org-babel-R-evaluate-session
  374. (session body result-type result-params column-names-p row-names-p)
  375. "Evaluate BODY in SESSION.
  376. If RESULT-TYPE equals `output' then return standard output as a
  377. string. If RESULT-TYPE equals `value' then return the value of the
  378. last statement in BODY, as elisp."
  379. (cl-case result-type
  380. (value
  381. (with-temp-buffer
  382. (insert (org-babel-chomp body))
  383. (let ((ess-local-process-name
  384. (process-name (get-buffer-process session)))
  385. (ess-eval-visibly-p nil))
  386. (ess-eval-buffer nil)))
  387. (let ((tmp-file (org-babel-temp-file "R-")))
  388. (org-babel-comint-eval-invisibly-and-wait-for-file
  389. session tmp-file
  390. (format org-babel-R-write-object-command
  391. (if row-names-p "TRUE" "FALSE")
  392. (if column-names-p
  393. (if row-names-p "NA" "TRUE")
  394. "FALSE")
  395. ".Last.value" (org-babel-process-file-name tmp-file 'noquote)))
  396. (org-babel-R-process-value-result
  397. (org-babel-result-cond result-params
  398. (with-temp-buffer
  399. (insert-file-contents tmp-file)
  400. (org-babel-chomp (buffer-string) "\n"))
  401. (org-babel-import-elisp-from-file tmp-file '(16)))
  402. column-names-p)))
  403. (output
  404. (mapconcat
  405. 'org-babel-chomp
  406. (butlast
  407. (delq nil
  408. (mapcar
  409. (lambda (line) (when (> (length line) 0) line))
  410. (mapcar
  411. (lambda (line) ;; cleanup extra prompts left in output
  412. (if (string-match
  413. "^\\([>+.]\\([ ][>.+]\\)*[ ]\\)"
  414. (car (split-string line "\n")))
  415. (substring line (match-end 1))
  416. line))
  417. (with-current-buffer session
  418. (let ((comint-prompt-regexp (concat "^" comint-prompt-regexp)))
  419. (org-babel-comint-with-output (session org-babel-R-eoe-output)
  420. (insert (mapconcat 'org-babel-chomp
  421. (list body org-babel-R-eoe-indicator)
  422. "\n"))
  423. (inferior-ess-send-input)))))))) "\n"))))
  424. (defun org-babel-R-process-value-result (result column-names-p)
  425. "R-specific processing of return value.
  426. Insert hline if column names in output have been requested."
  427. (if column-names-p
  428. (condition-case nil
  429. (cons (car result) (cons 'hline (cdr result)))
  430. (error "Could not parse R result"))
  431. result))
  432. ;;; async evaluation
  433. (defconst ob-session-async-R-indicator "'ob_comint_async_R_%s_%s'")
  434. (defun ob-session-async-org-babel-R-evaluate-session
  435. (session body result-type column-names-p row-names-p)
  436. "Asynchronously evaluate BODY in SESSION.
  437. Returns a placeholder string for insertion, to later be replaced
  438. by `org-babel-comint-async-filter'."
  439. (org-babel-comint-async-register
  440. session (current-buffer)
  441. "^\\(?:[>.+] \\)*\\[1\\] \"ob_comint_async_R_\\(.+?\\)_\\(.+\\)\"$"
  442. 'org-babel-chomp
  443. 'ob-session-async-R-value-callback)
  444. (cl-case result-type
  445. (value
  446. (let ((tmp-file (org-babel-temp-file "R-")))
  447. (with-temp-buffer
  448. (insert
  449. (org-babel-chomp body))
  450. (let ((ess-local-process-name
  451. (process-name (get-buffer-process session))))
  452. (ess-eval-buffer nil)))
  453. (with-temp-buffer
  454. (insert
  455. (mapconcat
  456. 'org-babel-chomp
  457. (list (format org-babel-R-write-object-command
  458. (if row-names-p "TRUE" "FALSE")
  459. (if column-names-p
  460. (if row-names-p "NA" "TRUE")
  461. "FALSE")
  462. ".Last.value"
  463. (org-babel-process-file-name tmp-file 'noquote))
  464. (format ob-session-async-R-indicator
  465. "file" tmp-file))
  466. "\n"))
  467. (let ((ess-local-process-name
  468. (process-name (get-buffer-process session))))
  469. (ess-eval-buffer nil)))
  470. tmp-file))
  471. (output
  472. (let ((uuid (md5 (number-to-string (random 100000000))))
  473. (ess-local-process-name
  474. (process-name (get-buffer-process session)))
  475. (ess-eval-visibly-p nil))
  476. (with-temp-buffer
  477. (insert (format ob-session-async-R-indicator
  478. "start" uuid))
  479. (insert "\n")
  480. (insert body)
  481. (insert "\n")
  482. (insert (format ob-session-async-R-indicator
  483. "end" uuid))
  484. (ess-eval-buffer nil ))
  485. uuid))))
  486. (defun ob-session-async-R-value-callback (params tmp-file)
  487. "Callback for async value results.
  488. Assigned locally to `ob-session-async-file-callback' in R
  489. comint buffers used for asynchronous Babel evaluation."
  490. (let* ((graphics-file (and (member "graphics" (assq :result-params params))
  491. (org-babel-graphical-output-file params)))
  492. (colnames-p (unless graphics-file (cdr (assq :colnames params)))))
  493. (org-babel-R-process-value-result
  494. (org-babel-result-cond (assq :result-params params)
  495. (with-temp-buffer
  496. (insert-file-contents tmp-file)
  497. (org-babel-chomp (buffer-string) "\n"))
  498. (org-babel-import-elisp-from-file tmp-file '(16)))
  499. (or (equal "yes" colnames-p)
  500. (org-babel-pick-name
  501. (cdr (assq :colname-names params)) colnames-p)))))
  502. ;;; ob-session-async-R.el ends here
  503. (provide 'ob-R)
  504. ;;; ob-R.el ends here