[R] how to use expression as function arguements?

2010-12-18 Thread casperyc

Hi all,

#
integ=function(f,n){ 
# computes vector y = f(x)
x=runif(1)
y=f
hatI=mean(y)
hatI
}
# example of use
integ(x^2+x+100,100)
#
it returns an error says no obj 'x'

how do I 'tell' R to treat 'f' as an input expression?

Thanks.

casper
-- 
View this message in context: 
http://r.789695.n4.nabble.com/how-to-use-expression-as-function-arguements-tp3093940p3093940.html
Sent from the R help mailing list archive at Nabble.com.

__
R-help@r-project.org 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] how to use expression as function arguements?

2010-12-18 Thread Duncan Murdoch

On 18/12/2010 2:34 PM, casperyc wrote:


Hi all,

#
integ=function(f,n){
# computes vector y = f(x)
x=runif(1)
y=f
hatI=mean(y)
hatI
}
# example of use
integ(x^2+x+100,100)
#
it returns an error says no obj 'x'

how do I 'tell' R to treat 'f' as an input expression?


In integ, you can get the unevaluated expression using

expr - substitute(f)

You can then evaluate it in the local context using

eval(expr)

So your integ function should be

integ=function(f,n){
# computes vector y = f(x)
x=runif(1)
y=eval( substitute(f) )
hatI=mean(y)
hatI
}

I can't help saying that this is bad style, though.  Using non-standard 
evaluation is usually a bad idea.  (There are examples like curve() in 
the base packages, but they are often criticized.)


A user should be able to expect that the x in

 integ(x^2+x+100,100)

refers to his own local variable named x, it shouldn't be a magic name.

Much better style is to require that the first argument is a function 
that takes a single argument; then you'd write your integ as


integ=function(f,n){
# computes vector y = f(x)
x=runif(1)
y=f(x)
hatI=mean(y)
hatI
}

and call it as

integ(function(x) x^2+x+100,100)

Doing this will be a lot more flexible and R-like in the long run.  For 
example, if you have two functions, you can say


f - function(x) x^2+x+100
g - function(x) x^2+x-100

and then do integ(f, 100); integ(g, 100).  The code I gave you would not 
work if f and g were stored as expressions:


 f - expression(x^2+x+100)
 integ(f, 100)
[1] NA
Warning message:
In mean.default(y) : argument is not numeric or logical: returning NA

Duncan Murdoch

__
R-help@r-project.org 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.