[R] Function with 'data' parameter

Jim Lemon jim at bitwrit.com.au
Sun Feb 22 10:52:25 CET 2009


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?

Jim




More information about the R-help mailing list