[R-sig-Geo] Call and Eval function inside R
Luca Morandini
lmorandini at ieee.org
Wed Jul 13 08:57:30 CEST 2011
On 07/12/2011 10:29 PM, Narayani Barve wrote:
>
> I am writing a function where I want to supply a variable which contains a
> condition to be evaluated inside the function. For example, I have a hourval
> variable containing values like 0, 3, 6, 9, 18, 3, 6, 9, 18 0, 3, 18 ... I
> want to select the indices where hourval variable matches to 0, 6.. This 0,
> 6 could change depending upon some other parameters. Basically they are not
> fixed always. So I pass a variable g1 = call("which", (hourval==0 | hourval
> == 6)). I want this statement to be evaluated in the program. Hence I use
> the statement x1 = eval(g1). Obviously, when I pass the variable g1, that
> time hourval variable is not generated, but it is generated just before the
> eval(g1) statement. I get error, object 'hourval' not found. Is there any
> other way to solve this problem.
The call function's arguments are evaluated at definition, hence hourval should be
defined beforehand.
An exmaple:
remove(c(a, b, c))
fmean<-call("mean", c(a, b, c)) # Error, a,b,c are not defined
a<-1
b<-2
c<-3
fmean<-call("mean", c(a, b, c)) # OK, a,b,c are defined
g<-function(f) {
eval(f)
}
g(fmean) # Returns 2
a<--1
b<-0
c<-1
g(fmean) # Returns 2 as well, since a,b,c are evaluated at definition time
Regards,
Luca Morandini
http://www.lucamorandini.it
More information about the R-sig-Geo
mailing list