[R] how to use expression as function arguements?

Duncan Murdoch murdoch.duncan at gmail.com
Sat Dec 18 22:13:55 CET 2010


On 18/12/2010 2:34 PM, casperyc wrote:
>
> Hi all,
>
> #####################################
> integ=function(f,n){
> 	# computes vector y = f(x)
> 	x=runif(10000)
> 	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(10000)
	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(10000)
	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



More information about the R-help mailing list