Expression evaluation not working inside a function (weird)

You can copy/paste the following code on a R script file:

myeval = function(code) {
  eval(parse(text = code))
}

### FAILS ###

test = function() {
  a = 5
  b = myeval(sprintf("b = a + 3")) # Raises this error: Error in eval(parse(text = code)) : object 'a' not found 
  return (b)
}

c = test()

print(c)

### SUCCESS ###

d = 5
e = myeval(sprintf("d + 3"))
print(e)

My Problem is: I'm getting an error when using myeval inside a function. However it works when it is outside a function.

Any idea on how to make eval work inside a function?

Thanks!

Ok, here the answer:

myeval = function(code, envir = NULL) {
  eval(parse(text = code), envir = envir)
}

test = function() {
  a = 5
  b = myeval(sprintf("a + 3"), environment())
  return (b)
}

c = test()

print(c)

Thanks!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.