Skip to content

Function with 'data' parameter

4 messages · greggallen at gmail.com, Jim Lemon, Gavin Simpson

#
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?

Greg.
#
Greg wrote:
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?

Jim
#
On Sun, 2009-02-22 at 20:52 +1100, Jim Lemon wrote:
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
#
Thanks, worked like a charm.

Greg.
On Feb 22, 1:58?pm, Gavin Simpson <gavin.simp... at ucl.ac.uk> wrote: