[R] seeking help with with()

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Aug 27 15:08:19 CEST 2003


On Wed, 27 Aug 2003, Simon Fear wrote:

> I tried to define a function like:
> 
> fnx <- function(x, by.vars=Month)
>   print(by(x, by.vars, summary))
> 
> But this doesn't work (does not find x$Month; unlike other functions,
> such as
> subset(), the INDICES argument to "by" does not look for variables in
> dataset
> x. Is fully documented, but I forget every time). So I tried using
> "with":
> 
> fnxx <- function(x, by.vars=Month)
>   print(with(x, by(x, by.vars, summary)))
> 
> Still fails to find object x$Month. 

That's not the actual error message, is it?

> I DO have a working solution (below) - this post is just to ask: Can
> anyone
> explain what happened to the with()?

Nothing!

by.vars is a variable passed to fnxx, so despite lazy evaluation, it is
going to be evaluated in the environment calling fnxx().  If that fails to
find it, it looks for the default value, and evaluates that in the
environment of the body of fnxx.  It didn't really get as far as with.

(I often forget where default args are evaluated, but I believe that is 
correct in R as well as in S.)

I think you intended Months to be a name and not a variable.  With

X <- data.frame(z=rnorm(20), Month=factor(rep(1:2, each=10)))

fnx <- function(x, by.vars="Month")
   print(by(x, x[by.vars], summary))

will work, as will

fnx <- function(x, by.vars=Month)
   print(by(x, x[deparse(substitute(by.vars))], summary))


-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list