ob-R.el 20 KB

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