%D \module
%D   [       file=m-r,
%D        version=2006.06.06,
%D          title=\CONTEXT\ Modules,
%D       subtitle=R Support,
%D         author={Johan Sandblom \& Hans Hagen},
%D           date=\currentdate,
%D      copyright={Johan Sandblom \& Hans Hagen}]
%C
%C This module is part of the \CONTEXT\ macro||package and is
%C therefore copyrighted by \PRAGMA. See mreadme.pdf for
%C details.

\unprotect

%D The following R-processor is a variation on Johan Sandblom's
%D prototype.
%D
%D We can combine both variants in one macro definition. Also, we
%D can minimize the number of runs by checking for a change.

%D JS: The call to R has \type {-q} in order to prevent banner,
%D \type {--save} to make sure it saves the workspace after the run,
%D \type {--restore} to make sure it reads any workspace from a
%D previous session.

%D An easier and better solution is to use the buffering mechanisms:

\def\Rbufferprefix{r-}

\newcounter\nofRfiles

\def\Rfile{\TEXbufferfile{\Rbufferprefix\nofRfiles}}%

\def\startR
  {\doglobal\increment\nofRfiles
   \dostartbuffer[\Rbufferprefix\nofRfiles][startR][stopR]}

\def\stopR
  {\doifmode{*\v!first}\runR
   \typefile{\Rfile.out}}

\def\startRhidden
  {\doglobal\increment\nofRfiles
   \dostartbuffer[\Rbufferprefix\nofRfiles][startRhidden][stopRhidden]}

\def\stopRhidden
  {\doifmode{*\v!first}\runR}

\def\runR
  {\executesystemcommand{texmfstart
      --ifchanged=\Rfile\space --direct R
      CMD BATCH -q --save --restore \Rfile\space \Rfile.out}}

\protect \doifnotmode{demo}{\endinput}

% Johan's test file:

\usemodule[r]

\def\R{R}

\setupcolors[state=start]

\setuptyping
 [Rtype]
 [color=darkgreen]

\starttext

First a test of whether the workspace is persistent:
bla

\startR
a <- "bla"
b <- "blabla"
ls()
\stopR

One \R run ends, another begins.

\startR
ls()
\stopR

Now follows a hidden \R run which cleans the R workspace

\startRhidden
rm(list=ls())
save.image()
\stopRhidden

What is in the workspace now?

\startR
ls()
\stopR

Then a small test of generating a graphic, in this case a pdf
\startR
ushape <- c(rexp(500000), 12-rexp(500000))
pdf("ushape.pdf")
par(mfrow=c(1,2))
hist(ushape)
plot(density(ushape), main="Density")
dev.off()
\stopR

The graphic \type{ushape.pdf} can be included in the standard \CONTEXT\ way
\startbuffer
\placefigure{An ugly distribution}{\externalfigure[ushape]}
\stopbuffer
\typebuffer
\getbuffer

\startR
x <- rnorm(900)
y <- rexp(900)
# test comment
f <- gl(9,9,900)
summary(aov(y~x+Error(f)))
library(lattice)
pdf("lattice.pdf")
xyplot(y~x|f)
dev.off()
\stopR

With \type{Sweave} lattice graphics calls must be enclosed in
\type{print()} statements but that is not necessary here.

\startbuffer
\placefigure[here]{Lattice graphics}{\externalfigure[lattice]}
\stopbuffer
\typebuffer
\getbuffer

A test string with nasty characters. In \R, the result of a statement
is not printed by default. Enclosing the statement in parentheses,
however causes the parser to see only the value of the statement and
applying the \type{print()} method.
\startR
(test <- ".*\\\\ [[{[{]{[{[{}\]\}=?!+%#|<|>@$")
cat(test)
\stopR

A combination
\startbuffer
\placefigure{A combination of two previously used graphics}{
\startcombination[2*1]
 {\externalfigure[ushape][width=.4\textwidth]}{The first graphic, rescaled}
 {\externalfigure[lattice][width=.4\textwidth]}{The second graphic, rescaled}}
\stopcombination
\stopbuffer
\typebuffer
\getbuffer

Testing a function definition.

\startR
a.df <- data.frame(a=1:2, b=rnorm(2))
a.df$a
testfunction <- function(a=NULL, ...) {
 for(i in 1:length(a)) {
   gsub(a[[i]], "([a-r]|[A-R])", "bla")}
 print(a)}
\stopR

What is in the workspace now?

\startR
ls()
\stopR

\stoptext
