[Rd] New simpleExit() condition (Was: Re: Can example() code stop the example without generating an error?)

Henrik Bengtsson hb at maths.lth.se
Tue Mar 14 15:04:30 CET 2006


On 3/14/06, Uwe Ligges <ligges at statistik.uni-dortmund.de> wrote:
> Henrik Bengtsson wrote:
>
> > Hi,
> >
> > does anyone know if it is possible to write example code (in Rd
> > examples) such that one can stop the example without generating an
> > error?  Example:
> >
> > code A
> > if (cond)
> >   niceStop()
> > code B
>
>
> What about
>
> code A
> if(cond){
>    code B
> }
>
> But maybe I do not get your point.

The purpose is to keep the code clean and I want to avoid nested if
statements.  Further conditions down the stream would make the code
quite ugly.  Pretty much for the same reason you use 'return()' and
'break'.

A nicer and more general solution is to have a subclass "simpleExit"
of "simpleCondition" and make source() catch such signals via
tryCatch(..., simpleExit=function(se) {...}).  Here is a complete
example:

simpleExit <- function(...) {
  cond <- simpleCondition(...)
  class(cond) <- c("simpleExit", class(cond))
  cond
}

exit <- function(...) {
  invisible(signalCondition(simpleExit(...)))
}

evalWithExit <- function(...) {
  tryCatch(..., simpleExit=function(cond) cond)
}

sourceWithExit <- function(...) {
  evalWithExit(source(...))
}


Examples:

> evalWithExit({cat("Hi\n");exit("Bye!");cat("there\n")}); cat("bye\n")
Hi
<simpleExit: Bye!>
bye

# Compare this...
> code <- 'cat("Hi\n"); exit("Bye!"); cat("there\n")'
> source(textConnection(code))
Hi
there

# ...with this:
> sourceWithExit(textConnection(code))
Hi
<simpleExit: Bye!>

R-core, would this be a useful feature to add to source()?

/Henrik

> Uwe Ligges
>
>
> > I know this sounds weird, but I would like some of my Rd examples to
> > run if and only if another package is available or if a certain large
> > Affymetrix data file is available.  One can put all of the example in
> > a function and return from the function if the package is not
> > available, but then all object assigned are lost. My best/cleanest
> > solution right now is to use break in a dummy for loop. Examples:
> >
> > for (z in 1) {
> >
> > code A
> > if (cond)
> >   break
> > code B
> >
> > }
> >
> > Other suggestions?  The solution must off course pass R CMD check.
> >
> > /Henrik
> >
> > PS. I know example() calls source(), but I'm not sure how R CMD check
> > does it. DS.
> >
> > ______________________________________________
> > R-devel at r-project.org mailing list
> > https://stat.ethz.ch/mailman/listinfo/r-devel
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>
>


--
Henrik Bengtsson
Mobile: +46 708 909208 (+1h UTC)



More information about the R-devel mailing list