I have a custom R environment
e = new.env()
e[["a"]] = function(x) b(x)
e[["b"]] = function(x) x + 1
Function b()
runs as expected.
> eval(parse(text = "b(1)"), envir = e)
[1] 2
But a(1)
throws an error.
> eval(parse(text = "a(1)"), envir = e)
Error in a(1) : could not find function "b"
How do I get eval(parse(text = "a(1)"), envir = e)
to work?
Your problem is that functions in R track the environment in which they were created. When you call the function()
statement outside of any other context, that function is being created in the global environment, and then you are assigning that function to a different environment, but it doesn't change where it was originally defined. Observe
e = new.env()
e[["a"]] = function(x) b(x)
environment(e[["a"]])
# <environment: R_GlobalEnv>
identical(e, environment(e[["a"]]))
# [1] FALSE
So that function will still use the global environment (not the e
environment) to resolve symbols. You can either explicitly change the environment with
environment(e[["a"]]) <- e
or just create it in the environment in the first place with evalq
evalq(a <- function(x) b(x), e)
evalq(b <- function(x) x + 1, e)
identical(e, environment(e[["a"]]))
# [1] TRUE
But are you sure this is really the best design for your problem? Seems a bit obtuse. Seeing eval(parse())
is usually a warning flag.