2

I have a function to evaluate a list of expressions and return a value based on which expression evaluates to true. Here are my expressions and values:

myexprs = list(expression(x <= 5), expression(x > 5 & x < 7), expression(x >= 7))
myvals = c(0, 1, 0)

I make a function that returns a function to evaluate a given number using myexprs and myvals. I use lapply to evaluate the expressions and return the value of myvals that matches which expression in myexprs evaluates to TRUE. If I do:

hscd = function(expr, score){
  function(x) score[unlist(lapply(expr, function(e) local(eval(e))))]
}  

test = hscd(myexprs, myvals)
test(4)
test(6)
test(7)

It works. However, if I do

hscd = function(expr, score){
  function(x) score[unlist(lapply(expr, local))]
}  

test = hscd(myexprs, myvals)
test(4)

It breaks.

My question: Why do I need to do local(eval(expr)) rather than just doing local(expr)? From the documentation it seems like the latter method should work too.


for completeness: If I do

hscd = function(expr, score){
  function(x) score[unlist(lapply(expr, eval))]
}  

test = hscd(myexprs, myvals)
test(4)

The function breaks because it looks for the variable x outside of the internal function, which mostly makes sense to me.

1 Answer 1

4

Note from the local help page that

[local] is equivalent to evalq except that its default argument creates a new, empty environment.

So what's happening is that your first parameter is being quoted. Note that these return the same result and neither evaluates the expression:

local(myexprs[[1]])
evalq(myexprs[[1]])

You could use eval() with an explicit environment rather than local()

hscd = function(expr, score){
  function(x) score[unlist(lapply(expr, eval, envir=environment()))]
}
2
  • Very clear. I wonder if this is why I could never get local to deliver the results I intended?
    – IRTFM
    Aug 5, 2015 at 19:19
  • Thank you! Part of my mistake was also misinterpreting parent.frame() and thinking it returned what is actually the result of environment(). This clears up the third example in my question too.
    – mikeck
    Aug 5, 2015 at 20:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.