开发者

Call and Eval function inside R

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 i开发者_如何转开发s generated just before the eval(g1) statement. I get error, object hourval not found. Is there any other way to solve this problem.

Thanks in advance, any help is appreciated.

Narayani Barve


Is this what you want?

> hourval <- c(0, 3, 6, 9, 18, 3, 6, 9, 18, 0, 3, 18)
> test <- c(0,6)
> which(hourval %in% test)
[1]  1  3  7 10

It took me a while to find it with this search strategy

library(fortunes)
fortune("parse")

but eventually got the one I remembered:

> fortune("parse")

If the answer is parse() you should usually rethink the question.
   -- Thomas Lumley
      R-help (February 2005)

Part of my difficulty was in the fact that I remembered the quote as having "eval(parse(".


This is what you seem to describe

f1 <- function(y) {
  hourval <- c(0, 3, 6, 9, 18, 3, 6, 9, 18, 0, 3, 18)
  eval(substitute(y))
}
f1( which(hourval %in% c(0,6)) )

But this is what I'd do instead.

f2 <- function(y) {
  hourval <- c(0, 3, 6, 9, 18, 3, 6, 9, 18, 0, 3, 18)
  which(hourval %in% y)
}
f2( c(0,6) )

But again, there's not enough information yet to know if either of these answer the question.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜