org-babel-R.el 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. ;;; org-babel-R.el --- org-babel functions for R code evaluation
  2. ;; Copyright (C) 2009 Eric Schulte
  3. ;; Author: Eric Schulte
  4. ;; Keywords: literate programming, reproducible research, R, statistics
  5. ;; Homepage: http://orgmode.org
  6. ;; Version: 0.01
  7. ;;; License:
  8. ;; This program 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, or (at your option)
  11. ;; any later version.
  12. ;;
  13. ;; This program 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. ;;
  18. ;; You should have received a copy of the GNU General Public License
  19. ;; along with GNU Emacs; see the file COPYING. If not, write to the
  20. ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  21. ;; Boston, MA 02110-1301, USA.
  22. ;;; Commentary:
  23. ;; Org-Babel support for evaluating R code
  24. ;;; Code:
  25. (require 'org-babel)
  26. (org-babel-add-interpreter "R")
  27. (defun org-babel-execute:R (body params)
  28. "Execute a block of R code with org-babel. This function is
  29. called by `org-babel-execute-src-block'."
  30. (message "executing R source code block...")
  31. (save-window-excursion
  32. (let ((vars (org-babel-ref-variables params))
  33. results)
  34. (org-babel-R-initiate-R-buffer)
  35. (mapc (lambda (pair) (org-babel-R-assign-elisp (car pair) (cdr pair))) vars)
  36. (org-babel-R-input-command body)
  37. (org-babel-R-last-value-as-elisp))))
  38. (defun org-babel-R-quote-tsv-field (s)
  39. "Quote field S for export to R."
  40. (if (stringp s)
  41. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  42. (format "%S" s)))
  43. (defun org-babel-R-assign-elisp (name value)
  44. "Read the elisp VALUE into a variable named NAME in the current
  45. R process in `org-babel-R-buffer'."
  46. (unless org-babel-R-buffer (error "No active R buffer"))
  47. (org-babel-R-input-command
  48. (if (listp value)
  49. (let ((transition-file (make-temp-file "org-babel-R-import"))
  50. has-header)
  51. ;; ensure VALUE has an orgtbl structure (depth of at least 2)
  52. (unless (listp (car value)) (setq value (list value)))
  53. (setq has-header (and (symbolp (cadr value)) (equal (cadr value) 'hline)))
  54. (with-temp-file transition-file
  55. (insert (orgtbl-to-tsv value '(:fmt org-babel-R-quote-tsv-field)))
  56. (insert "\n"))
  57. (format "%s <- read.table(\"%s\", header=%s, sep=\"\\t\", as.is=TRUE)"
  58. name transition-file (if has-header "TRUE" "FALSE")))
  59. (format "%s <- %s" name (org-babel-R-quote-tsv-field value)))))
  60. (defun org-babel-R-last-value-as-elisp ()
  61. "Return the last value returned by R as Emacs lisp."
  62. (let ((tmp-file (make-temp-file "org-babel-R")) result)
  63. (org-babel-R-input-command
  64. (format "write.table(.Last.value, file=\"%s\", sep=\"\\t\", na=\"nil\",row.names=FALSE, col.names=FALSE, quote=FALSE)"
  65. tmp-file))
  66. (with-temp-buffer
  67. (condition-case nil
  68. (progn
  69. (org-table-import tmp-file nil)
  70. (delete-file tmp-file)
  71. (setq result (mapcar (lambda (row)
  72. (mapcar #'org-babel-R-read row))
  73. (org-table-to-lisp))))
  74. (error nil))
  75. (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
  76. (if (consp (car result))
  77. (if (null (cdr (car result)))
  78. (caar result)
  79. result)
  80. (car result))
  81. result))))
  82. (defun org-babel-R-set-header-row (table)
  83. "Check whether the table appears to have (a) genuine
  84. user-supplied column names, or (b) default column names added
  85. automatically by R. In case (a), maintain the first row of the
  86. table as a header row and insert an hline. In case (b), remove
  87. the first row and return the org table without an hline."
  88. (if (or (string-equal (caar table) "V1")
  89. (string-equal (caar table) "x"))
  90. ;; write.table(1, col.names=TRUE) makes a colname called "x". I
  91. ;; think shows that this approach is too much of a hack: we
  92. ;; can't take some totally different action just because we see
  93. ;; an "x" there that might or might not be a automatic name.
  94. ;; The first row looks like it contains default column names
  95. ;; added by R. This condition could be improved so that it
  96. ;; checks whether the first row is ("V1" "V2" ... "V$n") where
  97. ;; $n is the number of columns.
  98. (cdr table)
  99. (cons (car table) (cons 'hline (cdr table)))))
  100. (defun org-babel-R-read (cell)
  101. "Strip nested \"s from around strings in exported R values."
  102. (org-babel-read (or (and (stringp cell)
  103. (string-match "\\\"\\(.+\\)\\\"" cell)
  104. (match-string 1 cell))
  105. cell)))
  106. ;; functions for evaluation of R code
  107. (defvar org-babel-R-buffer nil
  108. "Holds the buffer for the current R process")
  109. (defun org-babel-R-initiate-R-buffer ()
  110. "If there is not a current R process then create one."
  111. ;; DED: Ideally I think we should use ESS mechanisms for this sort
  112. ;; of thing. See ess-force-buffer-current.
  113. (unless (and (buffer-live-p org-babel-R-buffer) (get-buffer org-babel-R-buffer))
  114. (save-excursion
  115. (R)
  116. (setf org-babel-R-buffer (current-buffer))
  117. (org-babel-R-wait-for-output)
  118. (org-babel-R-input-command ""))))
  119. (defun org-babel-R-command-to-string (command)
  120. "Send a command to R, and return the results as a string."
  121. (org-babel-R-input-command command)
  122. (org-babel-R-last-output))
  123. (defun org-babel-R-input-command (command)
  124. "Pass COMMAND to the R process running in `org-babel-R-buffer'."
  125. (save-excursion
  126. (save-match-data
  127. (set-buffer org-babel-R-buffer)
  128. (goto-char (process-mark (get-buffer-process (current-buffer))))
  129. (insert command)
  130. (comint-send-input)
  131. (org-babel-R-wait-for-output))))
  132. (defun org-babel-R-wait-for-output ()
  133. "Wait until output arrives"
  134. (save-excursion
  135. (save-match-data
  136. (set-buffer org-babel-R-buffer)
  137. (while (progn
  138. (goto-char comint-last-input-end)
  139. (not (re-search-forward comint-prompt-regexp nil t)))
  140. (accept-process-output (get-buffer-process (current-buffer)))))))
  141. (defun org-babel-R-last-output ()
  142. "Return the last R output as a string"
  143. (save-excursion
  144. (save-match-data
  145. (set-buffer org-babel-R-buffer)
  146. (goto-char (process-mark (get-buffer-process (current-buffer))))
  147. (forward-line 0)
  148. (let ((raw (buffer-substring comint-last-input-end (- (point) 1)))
  149. output output-flag)
  150. (mapconcat
  151. (lambda (el)
  152. (if (stringp el)
  153. (format "%s" el)
  154. (format "%S" el)))
  155. (delq nil
  156. (mapcar
  157. (lambda (line)
  158. (unless (string-match "^>" line)
  159. (and (string-match "\\[[[:digit:]]+\\] *\\(.*\\)$" line)
  160. (match-string 1 line))))
  161. ;; drop first, because it's the last line of input
  162. (cdr (split-string raw "[\n\r]")))) "\n")))))
  163. (provide 'org-babel-R)
  164. ;;; org-babel-R.el ends here