[R] Using data and subset arguments in user-defined functions

Manuel Morales Manuel.A.Morales at williams.edu
Fri Oct 27 23:18:05 CEST 2006


Dear list,

A while ago, I posted a question asking how to use data or subset
arguments in a user-defined function. Duncan Murdoch suggested the
following solution in the context of a data argument:

data <- data.frame(a=c(1:10),b=c(1:10))

eg.fn <- function(expr, data) {
                  x <- eval(substitute(expr), envir=data)
                  return(mean(x))
}

eg.fn(a,data)

I've tried various approaches to add a subset argument to the example
above, but no luck. I'm looking for something like the following (but
that works!)

eg.fn2 <- function(expr, data, subset) {
                   data <- subset(data,subset)
                   x <- eval(substitute(expr), envir=data)
                   return(mean(x))
}

eg.fn2(a, data, subset=a>3)

This returns the error: 
"Error in eg.fn2(a, data, subset = a > 3) : 
        object "a" not found"

Any suggestions?

Thanks!

-- 
Manuel A. Morales
http://mutualism.williams.edu
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part
Url : https://stat.ethz.ch/pipermail/r-help/attachments/20061027/750c2230/attachment.bin 


More information about the R-help mailing list