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

2006-10-27 Thread Manuel Morales
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=a3)

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


signature.asc
Description: This is a digitally signed message part
__
R-help@stat.math.ethz.ch 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.


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

2006-10-27 Thread Duncan Murdoch
On 10/27/2006 5:18 PM, Manuel Morales wrote:
 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=a3)
 
 This returns the error: 
 Error in eg.fn2(a, data, subset = a  3) : 
 object a not found
 
 Any suggestions?

The problem is that subset needs to be evaluated with envir=data too. 
So this works:

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

It doesn't work to skip the first assignment and just put it inline into

subset(data, eval(substitute(subset), envir=data))

because subset() does nonstandard evaluation of the second argument.

Duncan Murdoch

__
R-help@stat.math.ethz.ch 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.