ob-R.el 13 KB

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