org-R.el 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  1. ;;; org-R.el --- Numerical computation and data visualisation for org-mode using R
  2. ;; Copyright (C) 2009
  3. ;; Free Software Foundation, Inc.
  4. ;; Author: Dan Davison <davison@stats.ox.ac.uk>
  5. ;; Keywords: org, R, ESS, tables, graphics
  6. ;; Homepage: http://www.stats.ox.ac.uk/~davison/software/org-R
  7. ;; Version: 0.05 2009-02-05
  8. ;;
  9. ;; This file is not part of GNU Emacs.
  10. ;;
  11. ;; This file is free software; you can redistribute it and/or modify
  12. ;; it under the terms of the GNU General Public License as published by
  13. ;; the Free Software Foundation; either version 3, or (at your option)
  14. ;; any later version.
  15. ;; This file is distributed in the hope that it will be useful,
  16. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. ;; GNU General Public License for more details.
  19. ;; You should have received a copy of the GNU General Public License
  20. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  21. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  22. ;;
  23. ;;; Commentary:
  24. ;; This file allows R (http://www.r-project.org) code to be applied to
  25. ;; emacs org-mode (http://orgmode.org) tables. When the
  26. ;; result of the analysis is a vector or matrix, it is output back
  27. ;; into the org-mode buffer as a new org table. Alternatively the R
  28. ;; code may be used to plot the data in the org table. It requires R to be
  29. ;; running in an inferior-ess-mode buffer (install Emacs Speaks
  30. ;; Statistics http://ess.r-project.org and issue M-x R).
  31. ;;
  32. ;;
  33. ;; The user interface is via two different options lines in the org
  34. ;; buffer. As is conventional in org-mode, these are lines starting
  35. ;; with `#+'. Lines starting with #+R: specify options in the
  36. ;; standard org style (option:value) and are used to specify certain
  37. ;; off-the-shelf transformations and plots of the table data. The
  38. ;; #+R: line is also used to specify the data to be analysed
  39. ;; (either an org table or a csv file), and to restrict the analysis
  40. ;; to certain columns etc. In lines starting #+RR: you can supply
  41. ;; literal R code, giving you full control over what you do with the
  42. ;; table. With point in the first #+R line, M-x org-R-apply
  43. ;; makes happen whatever has been specified in those lines.
  44. ;; The best documentation is currently the Worg tutorial:
  45. ;;
  46. ;; http://orgmode.org/worg/org-tutorials/org-R/org-R.php
  47. (defconst org-R-skeleton-funcall-1-arg
  48. "%s(x[%s]%s)"
  49. "Skeleton of a call to an R function.
  50. E.g. barplot(x[,3:5], names.arg=rownames(x))")
  51. (defconst org-R-skeleton-funcall-2-args
  52. "%s(x[,%s], x[,%s]%s)"
  53. "Skeleton of a call to an R function which can take x and y
  54. args.")
  55. (defconst org-R-write-org-table-def
  56. "write.org.table <- function (x, write.rownames = TRUE)
  57. {
  58. if(!is.null(dim(x)) && length(dim(x)) > 2)
  59. stop(\"Object must be 1- or 2-dimensional\") ;
  60. if(is.vector(x) || is.table(x) || is.factor(x) || is.array(x))
  61. x <- as.matrix(x) ;
  62. if(!(is.matrix(x) || inherits(x, c('matrix', 'data.frame')))) {
  63. invisible() ;
  64. print(x) ;
  65. stop(\"Object not recognised as 1- or 2-dimensional\") ;
  66. } ;
  67. if(is.null(colnames(x)))
  68. colnames(x) <- rep('', ncol(x)) ;
  69. if(write.rownames)
  70. x <- cbind(rownames(x), x) ;
  71. cat('|', paste(colnames(x), collapse = ' | '), '|\\n') ;
  72. cat('|', paste(rep('----', ncol(x)), collapse = '+'), '|\\n', sep = '') ;
  73. invisible(apply(x, 1, function(row) cat('|', paste(row, collapse = ' | '), '|\\n'))) ;
  74. }"
  75. "Definition of R function to write org table representation of R objects.
  76. To see a more human-readable version of this, look at the code,
  77. or type dput(write.org.table) RET at the R (inferior-ess-mode
  78. buffer) prompt.")
  79. (defun org-R-apply ()
  80. "Construct and evaluate an R function call.
  81. Construct an R function corresponding to the #+R: and #+RR:
  82. lines. R must be currently running in an inferior-ess-mode
  83. buffer. The function evaluates any user-supplied R code in the
  84. #+RR: line before the off-the-shelf actions specified in the #+R:
  85. line. The user-supplied R code can operate on a variable called x
  86. that is the org table represented as a data frame in R. Text
  87. output from the R process may be inserted into the org buffer, as
  88. an org table where appropriate."
  89. (interactive)
  90. (require 'ess)
  91. (save-excursion
  92. (beginning-of-line)
  93. (unless (looking-at "#\\+RR?:") (error "Point must be in a #+R or #+RR line"))
  94. (while (looking-at "#\\+RR?:") (forward-line -1))
  95. (forward-line)
  96. ;; For the rest of the code in this file we are based at the
  97. ;; beginning of the first #+R line
  98. ;; FIXME: if point is at the beginning of the #+RR? lines when
  99. ;; this function is called, then tabular output gets inserted,
  100. ;; leaving point up at the top of the tabular output.
  101. (let* ((options (org-R-get-options))
  102. (code (org-R-construct-code options))
  103. (infile (plist-get options :infile))
  104. (ext (if infile (file-name-extension infile)))
  105. csv-file)
  106. (if (string-equal ext "csv")
  107. (setq csv-file infile)
  108. (setq csv-file
  109. (org-R-export-to-csv
  110. (make-temp-file "org-R-tmp" nil ".csv") options)))
  111. (org-R-eval code csv-file options)
  112. (delete-other-windows) ;; FIXME
  113. (if (plist-get options :showcode) (org-R-showcode code)))))
  114. (defun org-R-apply-to-subtree ()
  115. "Call org-R-apply in every org-R block in current subtree."
  116. ;; This currently relies on re-search-forward leaving point after
  117. ;; the #+RR?: If point were at the beginning of the line, then
  118. ;; tabular input would get inserted leaving point above the #+RR?:,
  119. ;; and this would loop infinitely. Same for org-R-apply-to-buffer.
  120. (interactive)
  121. (save-excursion
  122. (org-back-to-heading)
  123. (while (re-search-forward
  124. "^#\\+RR?:"
  125. (save-excursion (org-end-of-subtree)) t)
  126. (org-R-apply)
  127. (forward-line)
  128. (while (looking-at "#\\+RR?")
  129. (forward-line)))))
  130. (defun org-R-apply-to-buffer ()
  131. "Call org-R-apply in every org-R block in the buffer."
  132. (interactive)
  133. (save-excursion
  134. (goto-char (point-min))
  135. (while (re-search-forward "^#\\+RR?:" nil t)
  136. (org-R-apply)
  137. (forward-line)
  138. (while (looking-at "#\\+RR?")
  139. (forward-line)))))
  140. (defun org-R-construct-code (options)
  141. "Construct the R function that implements the requested
  142. behaviour. The body of this function derives from two sources:
  143. 1. Explicit R code which is read from lines starting with
  144. #+RR: by org-R-get-user-code, and
  145. 2. Off-the-shelf code corresponding to options specified in the
  146. #+R: line. This code is constructed by
  147. org-R-off-the-shelf-code."
  148. (let ((user-code (org-R-get-user-code))
  149. (action (plist-get options :action)))
  150. (if (or (eq action 'tabulate) (eq action 'transpose))
  151. (setq options (plist-put options :output-to-buffer t)))
  152. (format "function(x){%sx}"
  153. (concat
  154. (when user-code (concat user-code ";"))
  155. (when action (concat (org-R-off-the-shelf-code options) ";"))))))
  156. (defun org-R-get-user-code (&optional R)
  157. "Read user-supplied R code from #+RR: lines"
  158. (let ((case-fold-search t))
  159. (save-excursion
  160. (while (looking-at "^#\\+\\(RR?:\\) *\\(.*\\)")
  161. (if (string= "RR:" (match-string 1))
  162. (setq R (concat R (when R ";") (match-string 2))))
  163. (forward-line))))
  164. R)
  165. (defun org-R-off-the-shelf-code (options)
  166. "Return R code implementing the actions requested in the
  167. #+R: lines."
  168. ;; This is a somewhat long function as it deals with several
  169. ;; different cases, corresponding to all the off-the-shelf actions
  170. ;; that have been implemented.
  171. (let* ((action (plist-get options :action))
  172. (cols (plist-get options :columns))
  173. (ncols (org-R-number-of-columns cols))
  174. (nxcols (nth 0 ncols))
  175. (nycols (nth 1 ncols))
  176. (cols-R (org-R-make-index-vectors cols))
  177. (xcols-R (nth 0 cols-R))
  178. (ycols-R (nth 1 cols-R))
  179. seq args largs extra-code title colour matrix-index)
  180. ;; I want this to affect options outside this function. Will it
  181. ;; necessarily do so? (not if plist-put adds to head of the
  182. ;; plist?)
  183. (setq options (plist-put options :nxcols nxcols))
  184. (cond ((eq action 'points)
  185. (setq action 'plot)
  186. (setq options (plist-put options :lines nil)))
  187. ((eq action 'lines)
  188. (setq action 'plot)
  189. (setq options (plist-put options :lines t))))
  190. (if (and (setq title (plist-get options :title)) (symbolp title))
  191. (setq title symbol-name title))
  192. (setq args (plist-put args :main (concat "\"" title "\"")))
  193. (if (setq colour (or (plist-get options :colour)
  194. (plist-get options :color)
  195. (plist-get options :col)))
  196. (setq args
  197. (plist-put args :col
  198. (concat "\"" (if (symbolp colour) (symbol-name colour) colour) "\""))))
  199. (setq largs
  200. (if (setq legend (plist-get options :legend))
  201. (plist-put largs :x
  202. (concat "\"" (if (symbolp legend) (symbol-name legend) legend) "\""))
  203. (plist-put largs :x "\"topright\"")))
  204. (cond
  205. ((null ycols-R)
  206. ;; single set of columns; implicit x values
  207. (if (null xcols-R)
  208. (setq xcols-R "" matrix-index "")
  209. (setq matrix-index (concat "," xcols-R)))
  210. (cond
  211. ;;----------------------------------------------------------------------
  212. ((eq action 'barplot)
  213. (if (eq nxcols 1)
  214. (progn
  215. (setq args (plist-put args :names.arg "rownames(x)"))
  216. (setq args (org-R-set-user-supplied-args args (plist-get options :args)))
  217. (format org-R-skeleton-funcall-1-arg
  218. "barplot" xcols-R
  219. (concat ", " (org-R-plist-to-R-args args))))
  220. (setq args (plist-put args :names.arg "colnames(x)"))
  221. (setq args (plist-put args :col "seq(nrow(x))"))
  222. (setq args (plist-put args :beside "TRUE"))
  223. (setq largs (plist-put largs :bty "\"n\""))
  224. ;; (setq largs (plist-put largs :lwd 10))
  225. (setq largs (plist-put largs :col "seq(nrow(x))"))
  226. (setq largs (plist-put largs :legend "rownames(x)"))
  227. (setq args (org-R-set-user-supplied-args args (plist-get options :args)))
  228. (concat (format org-R-skeleton-funcall-1-arg
  229. "barplot(as.matrix" matrix-index
  230. (concat "), " (org-R-plist-to-R-args args)))
  231. "; legend(" (org-R-plist-to-R-args largs) ")")))
  232. ;;----------------------------------------------------------------------
  233. ((eq action 'density)
  234. (if (and nxcols (> nxcols 1))
  235. (error "Multiple columns not implemented for action:%s" action))
  236. (setq args (plist-put args :xlab (concat "colnames(x)["xcols-R"]")))
  237. (setq args (org-R-set-user-supplied-args args (plist-get options :args)))
  238. (format org-R-skeleton-funcall-1-arg
  239. "plot(density" matrix-index
  240. (concat "), " (org-R-plist-to-R-args args))))
  241. ;;----------------------------------------------------------------------
  242. ((eq action 'hist)
  243. (if (and nxcols (> nxcols 1))
  244. (error "Multiple columns not implemented for action:%s" action))
  245. (setq args (plist-put args :xlab (concat "colnames(x)["xcols-R"]")))
  246. (setq args (org-R-set-user-supplied-args args (plist-get options :args)))
  247. (setq args (concat ", " (org-R-plist-to-R-args args)))
  248. (format org-R-skeleton-funcall-1-arg "hist" matrix-index args))
  249. ;;----------------------------------------------------------------------
  250. ((eq action 'image)
  251. (format org-R-skeleton-funcall-1-arg "image(as.matrix" matrix-index ")"))
  252. ;;----------------------------------------------------------------------
  253. ((eq action 'plot)
  254. (setq seq (concat "seq_along("xcols-R")"))
  255. (setq args (plist-put args :type (if (plist-get options :lines) "\"l\"" "\"p\"")))
  256. (setq args (plist-put args :ylab (concat "colnames(x)["xcols-R"]")))
  257. (setq args (concat ", " (org-R-plist-to-R-args args)))
  258. (concat (format org-R-skeleton-funcall-1-arg
  259. (if (eq nxcols 1) "plot" "matplot") matrix-index args)
  260. extra-code))
  261. ;;----------------------------------------------------------------------
  262. ((eq action 'tabulate)
  263. (concat
  264. (if (plist-get options :sort)
  265. (format org-R-skeleton-funcall-1-arg
  266. "x <- sort(table" xcols-R "), decreasing=TRUE")
  267. (format org-R-skeleton-funcall-1-arg "x <- table" matrix-index ""))
  268. (if (eq nxcols 1) "; x <- data.frame(value=names(x), count=x[])")))
  269. ;;----------------------------------------------------------------------
  270. ((eq action 'transpose)
  271. (format org-R-skeleton-funcall-1-arg "x <- t" matrix-index ""))
  272. ;;----------------------------------------------------------------------
  273. ;; Don't recognise action: option, try applying it as the name of an R function.
  274. (t (format org-R-skeleton-funcall-1-arg
  275. (concat "x <- " (symbol-name action)) matrix-index ""))))
  276. ;;----------------------------------------------------------------------
  277. (ycols-R
  278. ;; x and y columns specified
  279. (cond
  280. ;;----------------------------------------------------------------------
  281. ((eq action 'plot)
  282. (unless (eq nxcols 1) (error "Multiple x-columns not implemented for action:plot"))
  283. (setq args
  284. (plist-put
  285. args :ylab
  286. (concat "if(length("ycols-R") == 1) colnames(x)["ycols-R"] else ''")))
  287. (setq args (plist-put args :xlab (concat "colnames(x)["xcols-R"]")))
  288. (setq args (plist-put args :type (if (plist-get options :lines) "\"l\"" "\"p\"")))
  289. (setq args (concat ", " (org-R-plist-to-R-args args)))
  290. (setq seq (concat "seq_along("ycols-R")"))
  291. (setq largs (plist-put largs :col seq))
  292. (setq largs (plist-put largs :lty seq))
  293. (setq largs (plist-put largs :bty "\"n\""))
  294. (setq largs (plist-put largs :legend (concat "colnames(x)["ycols-R"]")))
  295. (setq extra-code
  296. (concat "; "
  297. "if(length("ycols-R") > 1) "
  298. "legend(" (org-R-plist-to-R-args largs) ")"))
  299. (concat (format org-R-skeleton-funcall-2-args
  300. (if (and (eq nxcols 1) (eq nycols 1)) "plot" "matplot")
  301. xcols-R ycols-R args)
  302. extra-code))
  303. ;;----------------------------------------------------------------------
  304. (t (error "action:%s requires a single set of columns" (symbol-name action))))))))
  305. (defun org-R-set-user-supplied-args (args user-args)
  306. "Set user-supplied values in arguments plist."
  307. (while (setq prop (pop user-args))
  308. (setq args (plist-put args prop (pop user-args))))
  309. args)
  310. (defun org-R-plist-to-R-args (plist)
  311. "Convert a plist into a string of R arguments."
  312. (let (arg-string arg)
  313. (while (setq arg (pop plist))
  314. (string-match ":\\(\.*\\)" (symbol-name arg))
  315. (setq arg (match-string 1 (symbol-name arg)))
  316. (setq arg-string
  317. (concat
  318. (if arg-string (concat arg-string ", "))
  319. (format "%s=%s" arg (pop plist)))))
  320. arg-string))
  321. (defun org-R-alist-to-R-args (alist)
  322. "Convert an alist of (argument . val) pairs into a string of R arguments.
  323. The alist is something like
  324. '((arg1 . 1)
  325. (arg2 . a))
  326. This isn't used, but it seems much nicer than
  327. my plist equivalent. Is there a better way to write the plist
  328. version?
  329. "
  330. (mapconcat
  331. 'identity
  332. (mapcar (lambda(pair) (format "%s = %s" (car pair) (cdr pair))) alist)
  333. ", "))
  334. (defun org-R-make-index-vectors (cols)
  335. "COLS is the lisp form given by the `columns:' option. It may
  336. take the following forms:
  337. 1. integer atom - the number of the column
  338. 2. symbol/string atom - the name of the column
  339. 3. list of length 1 - same as 1 or 2 above
  340. 4. list of length > 1 - specification of multiple columns as 1 or 2 above, unless it is
  341. 5. list of 2 lists - each list specifies (possibly multiple) columns
  342. In cases 1-4 this function returns a list of length 1, containing
  343. the R index vector as a string. In case 5 this function returns a
  344. list of two such index vectors.
  345. In cases 1 - 4, when a bivariate plot is requested such as by
  346. `action:lines', the x values are implicit, i.e
  347. 1,2,...,number-of-rows.
  348. In case 4, an attempt is made to do something sensible with the
  349. multiple columns, e.g. for `action:lines' they will be plotted
  350. together on the same graph against the implicit x values, and for
  351. `action:barplot' the bars corresponding to a single row will be
  352. stacked on top of each other, or placed side by side, depending
  353. on the value of the `beside' option.
  354. For `action:tabulate', if 2 columns are selected, a
  355. two-dimensional table is created. If more than 2, then the
  356. appropriately dimensioned table is computed and inserted using
  357. the standard text representation of multi-dimensional arrays used
  358. by R (as org does not currently have tables of dimension > 2).
  359. The straightforward case of case 5 is that both lists are of
  360. length 1. For `action:plot' and `action:lines' these specify the
  361. y and x coordinates of the points to be plotted or joined by
  362. lines.
  363. The intention is that `org-R-apply' does something
  364. corresponding to what would happen if you did the following in R:
  365. fun(x=tab[,xcols], y=tab[,ycols])
  366. where fun is the R function implementing the desired
  367. action (plotting/computation), tab is the org table, xcols are
  368. the columns specified in cases 1-4 above, and ycols are the
  369. second set of columns which might have been specified under case
  370. 5 above. For relevant R documentation see the help page
  371. associated with the function xy.coords, e.g. by typing ?xy.coords
  372. at the R prompt.
  373. The following won't work with case 5: `tabulate'
  374. "
  375. (defun org-R-make-index-vector (cols)
  376. "Return the R indexing vector (as a string) corresponding to
  377. the lisp form COLS. In this function, COLS is a either a list of
  378. atoms, or an atom, i.e. in the form of cases 1-4"
  379. (when cols
  380. (let (to-stringf)
  381. (unless (listp cols) (setq cols (list cols)))
  382. (setq to-stringf
  383. (cond ((car (mapcar 'symbolp cols))
  384. (lambda (symbol) (concat "\"" (symbol-name symbol) "\"")))
  385. ((car (mapcar 'integerp cols))
  386. 'int-to-string)
  387. ((car (mapcar 'stringp cols))
  388. (lambda (string) (concat "\"" string "\"")))
  389. (t (error "Column selection should be symbol, integer or string: %S" cols))))
  390. (concat (when (> (length cols) 1) "c(")
  391. (mapconcat to-stringf cols ",")
  392. (when (> (length cols) 1) ")")))))
  393. (if (and (listp cols) (listp (car cols)))
  394. (mapcar 'org-R-make-index-vector cols) ;; case 5
  395. (list (org-R-make-index-vector cols)))) ;; other cases
  396. (defun org-R-number-of-columns (cols)
  397. (defun f (c) (if (listp c) (length c) 1))
  398. (if (and (listp cols) (listp (car cols)))
  399. (mapcar 'f cols)
  400. (list (f cols))))
  401. (defun org-R-eval (R-function csv-file options)
  402. "Apply an R function to tabular data and receive output as an org table.
  403. R-FUNCTION is a string; it may be simply the name of an
  404. appropriate R function (e.g. \"summary\", \"plot\"), or a
  405. user-defined anonymous function of the form
  406. \"(function(data.frame) {...})\". It will receive as its first
  407. argument the org table as an R 'data frame' -- a table-like
  408. structure which can have columns containing different types of
  409. data -- numeric, character etc.
  410. The R function may produce graphical and/or text output. If it
  411. produces text output, and the replace:t is specified, and if
  412. there is a table immediately above the #+R lines, then it is
  413. replaced by the text output. Otherwise the text output is
  414. inserted above the #+R lines.
  415. "
  416. (let ((transit-buffer "org-R-transit")
  417. (infile (plist-get options :infile))
  418. (output-file (plist-get options :outfile))
  419. (title (plist-get options :title))
  420. output-format graphics-output-file width height)
  421. (unless (not output-file)
  422. ;; We are writing output to file. Determine file format and
  423. ;; location, and open graphics device if necessary.
  424. (if (string-match
  425. "\\(.*\.\\)?\\(org\\|png\\|jpg\\|jpeg\\|pdf\\|ps\\|bmp\\|tiff\\)$"
  426. output-file)
  427. (setq output-format (match-string 2 output-file))
  428. (error "Did not recognise file name suffix %s as available output format"
  429. (match-string 2 output-file)))
  430. (unless (match-string 1 output-file)
  431. ;; only suffix provided: store in org-attach dir
  432. (require 'org-attach)
  433. (let ((temporary-file-directory (org-attach-dir t)))
  434. (setq output-file
  435. (make-temp-file
  436. "org-R-output-" nil (concat "." output-format)))))
  437. (if (eq output-format "jpg") (setq output-format "jpeg"))
  438. (setq graphics-output-file (not (string-equal output-format "org")))
  439. (if graphics-output-file ;; open the graphics device
  440. (ess-execute
  441. (concat output-format "(file=\"" output-file "\""
  442. (if (setq width (plist-get options :width))
  443. (format ", width=%d" width))
  444. (if (setq height (plist-get options :height))
  445. (format ", height=%d" height)) ")"))))
  446. ;; Apply R code to table (which is now stored as a csv file)
  447. ;; does it matter whether this uses ess-command or ess-execute?
  448. ;; First evaluate function definition for R -> org table conversion
  449. (ess-execute (replace-regexp-in-string "\n" " " org-R-write-org-table-def)
  450. nil transit-buffer)
  451. ;; FIXME: why not eval the function def together with the function call
  452. ;; as in the commented out line below (it didn't work for some reason)
  453. (ess-execute
  454. (concat
  455. ;; (replace-regexp-in-string "\n" " " org-R-write-org-table-def) ";"
  456. (org-R-make-expr R-function csv-file options)) nil transit-buffer)
  457. (save-excursion
  458. (set-buffer (concat "*" transit-buffer "*"))
  459. (unless (or (looking-at "$")
  460. (string-equal (buffer-substring-no-properties 1 2) "|"))
  461. (error "Error in R evaluation:\n%s" (buffer-string))))
  462. (if csv-file
  463. (unless (and infile
  464. (string-equal (file-name-extension infile) "csv"))
  465. (delete-file csv-file)))
  466. (if graphics-output-file (ess-execute "dev.off()")) ;; Close graphics device
  467. (unless (or graphics-output-file
  468. (not (plist-get options :output-to-buffer)))
  469. ;; Send tabular output to a org buffer as new org
  470. ;; table. Recall that we are currently at the beginning of the
  471. ;; first #+R line
  472. (if (and output-file graphics-output-file)
  473. (error "output-to-buffer and graphics-output-file both t"))
  474. (save-excursion
  475. (if output-file
  476. (progn (set-buffer (find-file-noselect output-file))
  477. (delete-region (point-min) (point-max)))
  478. (if (plist-get options :replace)
  479. (progn ;; kill a table iff in one or one ends on the previous line
  480. (delete-region (org-table-begin) (org-table-end))
  481. (save-excursion
  482. (forward-line -1)
  483. (if (looking-at "#\\+TBLNAME")
  484. (delete-region (point) (1+ (point-at-eol))))))))
  485. (if title (insert "#+TBLNAME:" title "\n"))
  486. (insert-buffer-substring (concat "*" transit-buffer "*"))
  487. (org-table-align)
  488. (if output-file (save-buffer))))
  489. ;; We might be linking to graphical output, or to org output in
  490. ;; another file. Either way, point is still at the beginning of
  491. ;; the first #+R line.
  492. (unless (not output-file)
  493. (save-excursion
  494. (forward-line -1)
  495. (if (looking-at "\\[\\[file:")
  496. (delete-region (point) (1+ (point-at-eol)))))
  497. (insert (org-make-link-string
  498. (concat "file:" output-file)
  499. (unless (plist-get options :inline)
  500. (or title (concat output-format " output")))) "\n"))
  501. (kill-buffer (concat "*" transit-buffer "*"))))
  502. (defun org-R-export-to-csv (csv-file options)
  503. "Find and export org table to csv.
  504. If the intable: option has not been supplied, then the table must
  505. end on the line immediately above the #+R lines. Otherwise,
  506. the remote table referenced by the intable: option is found using
  507. org-R-find-table. If options:infile has been set then this is the
  508. org file containing the table. See the docstring of
  509. org-R-find-table for details."
  510. (let ((tbl-name-or-id (plist-get options :intable))
  511. (org-file (plist-get options :infile)) tbl-marker)
  512. (if (and org-file
  513. (not (string-equal (file-name-extension org-file) "org")))
  514. (error "File %s extension is not .csv so should be .org"))
  515. (save-excursion
  516. (if tbl-name-or-id
  517. ;; a remote table has been specified -- move into it
  518. (progn
  519. (if org-file (set-buffer (find-file-noselect org-file)))
  520. (setq tbl-marker (org-R-find-table tbl-name-or-id 'marker))
  521. (set-buffer (marker-buffer tbl-marker))
  522. (goto-char (marker-position tbl-marker)))
  523. (forward-line -1)) ;; move into table above
  524. (if (looking-at "[ \t]*|")
  525. (progn (org-table-export csv-file "orgtbl-to-csv") csv-file)
  526. nil))))
  527. (defun org-R-find-table (name-or-id &optional markerp)
  528. "Return location of a table.
  529. NAME-OR-ID may be the name of a
  530. table in the current file as set by a \"#+TBLNAME:\" directive.
  531. The first table following this line will then be used.
  532. Alternatively, it may be an ID referring to any entry, perhaps in
  533. a different file. In this case, the first table in that entry
  534. will be referenced. The location is returned as a marker pointing
  535. to the beginning of the first line of the table.
  536. This is taken from the first part of org-table-get-remote-range
  537. in org-table.el.
  538. "
  539. (cond
  540. ((symbolp name-or-id) (setq name-or-id (symbol-name name-or-id)))
  541. ((numberp name-or-id) (setq name-or-id (number-to-string name-or-id))))
  542. (save-match-data
  543. (let ((id-loc nil) (case-fold-search t) buffer loc)
  544. (save-excursion
  545. (save-restriction
  546. (widen)
  547. (save-excursion
  548. (goto-char (point-min))
  549. (if (re-search-forward
  550. (concat "^#\\+TBLNAME:[ \t]*" (regexp-quote name-or-id) "[ \t]*$")
  551. nil t)
  552. ;; OK, we've found a matching table name in this buffer.
  553. (setq buffer (current-buffer) loc (match-beginning 0))
  554. ;; It's not a table name in this buffer. It must be an entry id.
  555. ;; obtain a marker pointing to it.
  556. (setq id-loc (org-id-find name-or-id 'marker)
  557. buffer (marker-buffer id-loc)
  558. loc (marker-position id-loc))
  559. (move-marker id-loc nil))) ;; disable the marker
  560. ;; (switch-to-buffer buffer)
  561. (set-buffer buffer)
  562. ;; OK, so now we're in the right buffer, and loc is either
  563. ;; the beginning of the #+TBLNAME line, or the location of the entry
  564. ;; either way we need to search forward to get to the beginning of the table
  565. (save-excursion
  566. (save-restriction
  567. (widen)
  568. (goto-char loc)
  569. (forward-char 1)
  570. ;; The following regexp search finds the beginning of
  571. ;; the next table in this entry. If it gets to the next
  572. ;; entry before the next table, then it signals failure.
  573. (unless (and (re-search-forward "^\\(\\*+ \\)\\|[ \t]*|" nil t)
  574. (not (match-beginning 1)))
  575. (error "Cannot find a table at NAME or ID %s" name-or-id))
  576. (if markerp
  577. (move-marker (make-marker) (point-at-bol) (current-buffer))
  578. (error "Option to return cons cell not implemented.
  579. It should return (file-name . position) to be
  580. consistent with functions in org-id.el")))))))))
  581. (defun org-R-make-expr (R-function csv-file options)
  582. "Construct R code to read data, analyse it and write output."
  583. (let ((rownames (plist-get options :rownames))
  584. (colnames (plist-get options :colnames))
  585. (action (plist-get options :action))
  586. (replace (plist-get options :replace)))
  587. (if (and csv-file (symbolp csv-file))
  588. (setq csv-file (symbol-name csv-file)))
  589. (format "write.org.table((%s)(%s), write.rownames=%s)"
  590. R-function
  591. (if csv-file
  592. (format
  593. "read.csv(\"%s\", header=%s, row.names=%s)"
  594. csv-file
  595. ;; Do we treat first row as colnames? Yes by default
  596. ;; FIXME: should really check for hline
  597. (if colnames "TRUE" "FALSE")
  598. ;; Do we use a column as rownames? Not unless rownames: is specified
  599. (if rownames "1" "NULL"))
  600. "NULL")
  601. ;; Do we write rownames into org table?
  602. (cond ((eq action 'tabulate)
  603. (if (eq (plist-get options :nxcols) 1) "FALSE" "TRUE"))
  604. ((eq action 'transpose) (if colnames "TRUE" "FALSE"))
  605. (rownames "TRUE")
  606. (t "TRUE")))))
  607. (defun org-R-get-options ()
  608. "Parse the #+R: lines and return the options and values as a p-list."
  609. (let ((opts '(
  610. (:infile . "infile")
  611. (:intable . "intable")
  612. (:rownames . "rownames")
  613. (:colnames . "colnames")
  614. (:columns . "columns")
  615. (:action . "action")
  616. (:args . "args")
  617. (:outfile . "outfile")
  618. (:replace . "replace")
  619. (:title . "title")
  620. (:legend . "legend")
  621. (:colour . "colour")
  622. (:color . "color")
  623. (:col . "col")
  624. (:height . "height")
  625. (:width . "width")
  626. (:lines . "lines")
  627. (:sort . "sort")
  628. (:inline . "inline")
  629. (:output-to-buffer . "output-to-buffer")
  630. (:showcode . "showcode")))
  631. (regexp ":\\(\"[^\"]*\"\\|(([^)]*) *([^)]*))\\|([^)]*)\\|[^ \t\n\r;,.]*\\)")
  632. (case-fold-search t) p)
  633. ;; FIXME: set default options properly
  634. (setq p (plist-put p :output-to-buffer t)) ;; FIXME: hack: null options plist is bad news
  635. (setq p (plist-put p :replace t))
  636. (setq p (plist-put p :rownames nil))
  637. (setq p (plist-put p :colnames t))
  638. (setq p (plist-put p :inline nil))
  639. (save-excursion
  640. (while (looking-at "^#\\+\\(RR?:+\\) *\\(.*\\)")
  641. (if (string= "R:" (match-string 1))
  642. (setq p (org-R-add-options-to-plist p (match-string 2) opts regexp)))
  643. (forward-line)))
  644. p))
  645. (defun org-R-add-options-to-plist (p opt-string op regexp)
  646. "Parse a #+R: line and set values in the property list
  647. p. This function is adapted from similar functions in org-exp.el
  648. and org-plot.el. It might be a good idea to have a single
  649. function serving these three files' needs."
  650. ;; Adapted from org-exp.el and org-plot.el
  651. (let (o)
  652. (when opt-string
  653. (while (setq o (pop op))
  654. (if (string-match
  655. (concat (regexp-quote (cdr o)) regexp)
  656. opt-string)
  657. (setq p (plist-put p (car o)
  658. (car (read-from-string
  659. (match-string 1 opt-string)))))))))
  660. p)
  661. (defun org-R-sanitise-options (options)
  662. (error "not used yet")
  663. (let (should-be-strings '(title legend colour color col csv)))
  664. )
  665. (defun org-R-showcode (R)
  666. "Display R function constructed by org-R in a new R-mode
  667. buffer"
  668. (split-window-vertically)
  669. (switch-to-buffer "*org-table.R*")
  670. (kill-region (point-min) (point-max))
  671. (R-mode)
  672. (insert (replace-regexp-in-string
  673. ";" "\n" (replace-regexp-in-string "\\([{}]\\)" "\n\\1\n" R)))
  674. ;; (mark-whole-buffer)
  675. ;; (indent-region)
  676. ;; why doesn't that do what I hoped?
  677. )
  678. (defun org-R-get-remote-range (name-or-id form)
  679. "This is a refactoring of Carsten's original version. I have
  680. extracted the first bit of his function and named it
  681. org-R-find-table (which would presumably be called
  682. something like org-table-find-table or org-id-find-table if this
  683. were accepted).
  684. Get a field value or a list of values in a range from table at ID.
  685. NAME-OR-ID may be the name of a table in the current file as set by
  686. a \"#+TBLNAME:\" directive. The first table following this line
  687. will then be used. Alternatively, it may be an ID referring to
  688. any entry, possibly in a different file. In this case, the first table
  689. in that entry will be referenced.
  690. FORM is a field or range descriptor like \"@2$3\" or or \"B3\" or
  691. \"@I$2..@II$2\". All the references must be absolute, not relative.
  692. The return value is either a single string for a single field, or a
  693. list of the fields in the rectangle."
  694. (let ((tbl-marker (org-R-find-table name-or-id 'marker))
  695. org-table-column-names org-table-column-name-regexp
  696. org-table-local-parameters org-table-named-field-locations
  697. org-table-current-line-types org-table-current-begin-line
  698. org-table-current-begin-pos org-table-dlines
  699. org-table-hlines org-table-last-alignment
  700. org-table-last-column-widths org-table-last-alignment
  701. org-table-last-column-widths tbeg)
  702. (save-excursion
  703. (set-buffer (marker-buffer tbl-marker))
  704. (goto-char (marker-position tbl-marker))
  705. (org-table-get-specials)
  706. (setq form (org-table-formula-substitute-names form))
  707. (if (and (string-match org-table-range-regexp form)
  708. (> (length (match-string 0 form)) 1))
  709. (save-match-data
  710. (org-table-get-range (match-string 0 form) (point) 1))
  711. form))))
  712. (provide 'org-R)