[R] Function with 'data' parameter

Gavin Simpson gavin.simpson at ucl.ac.uk
Sun Feb 22 19:58:58 CET 2009


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
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: This is a digitally signed message part
URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20090222/9ee6cd0c/attachment-0002.bin>


More information about the R-help mailing list