On Sun, 2009-02-22 at 20:52 +1100, Jim Lemon wrote:
> Greg wrote:
> > I'm trying to write a simple function with a data parameter.
> >
> > tfun <- function(x, y, data = NULL) {
> >     if(missing(data))
> >             dt <- data.frame(x=x, group=y)
> >     else {
> >             dt <- with(data, data.frame(x=x, group=y))
> >     }
> >
> >     return(dt)
> > }
> >
> > If I pass variables "weight" and "grp" from a data.frame, d, like
> > this: tfun(d$weight, d$grp), the function works.  However, if I try to
> > do the same thing by supplying d, like this: tfun(weight, grp,
> > data=d), I receive the following error:
> >
> > Error in data.frame(x = x, group = y) : object "weight" not found
> >
> > Can someone please tell me what I'm doing wrong?
> >
> >   
> Hi Greg,
> In your function definition, the data argument isn't missing, it's NULL. 
> You have to test like this:
> 
> if(is.null(data)) ...
> 
> Does that fix it?

No, because x and y are still being evaluated and are not present
anywhere but within 'd'. (I converted the function definition to
function(x, y, data) and checked that it was executing the else clause
when data was *not* missing.)

You could do:

## dummy data
set.seed(1234)
d <- data.frame(weight = rnorm(10),
                grp = rnorm(10))

tfun2 <- function(x, y, data) {
        x <- deparse(substitute(x))
        y <- deparse(substitute(y))
        if(missing(data))
                dt <- data.frame(x=x, group=y)
        else {
                dt <- with(data, data.frame(x=data[[x]], group=data[[y]]))
        }
        return(dt)
}

tfun2(weight, grp, data = d)

but that seems a little ugly. Alternatively, make use of a model formula
and in-built functionality

tfun3 <- function(formula, data) {
        dat <- model.frame(formula, data)
        names(dat) <- c("x", "group")
        return(dat)
}

tfun3(weight ~ grp, data = d)

HTH

G

-- 
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
 Dr. Gavin Simpson             [t] +44 (0)20 7679 0522
 ECRC, UCL Geography,          [f] +44 (0)20 7679 0565
 Pearson Building,             [e] gavin.simpsonATNOSPAMucl.ac.uk
 Gower Street, London          [w] http://www.ucl.ac.uk/~ucfagls/
 UK. WC1E 6BT.                 [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%

Attachment: signature.asc
Description: This is a digitally signed message part

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to