Can anyone explain what causes the error in the last line of the code? Is it a bug?
> ll <- list(a=1, b=2)
> ee <- as.environment(ll)
> ee
<environment: 0x0000000004d35810>
> ls(ee)
[1] "a" "b"
> with(ee, a)
[1] 1
> with(ee, a - b)
Error in eval(expr, envir, enclos) : could not find function "-"
>
This is due to R’s scoping. It needs to find the function
"-"(). You told R to evaluate your expression in the environmentee. There is no function"-"()there, so proceeded to the parent environment ofee, which is:where there is no function
"-"()either. As there is no parent environment to the empty environmentR gave up the search and threw an error.
We can solve the problem by attaching a parent environment to
eewhere R can find the function:But I think this would be more natural, to set the parent of
eeto be the global environment:aandbwill always be found ineeas that is the first scoping environment encountered, but the functions can be looked up in the usual place, as if running this at the command line. If you are doing this in a function call, then you’ll need to assign the correct environment.