org-R.el 32 KB

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