org-babel-R.el 7.3 KB

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