"with" functional behavior
Can someone explain what causes the error in the last line of code? This is mistake?
> 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 the use of region R. He must find the function "-"() . You told R to evaluate your expression in ee . There is no function "-"() , so I switched to the parent environment ee , which:
> parent.env(ee) <environment: R_EmptyEnv> where there is no function "-"() . Since there is no parent environment in an empty environment
> parent.env(parent.env(ee)) Error in parent.env(parent.env(ee)) : the empty environment has no parent R refused the search and made a mistake.
We can solve the problem by connecting the parent environment with ee , where R can find the function:
> parent.env(ee) <- .BaseNamespaceEnv > with(ee, a - b) [1] -1 But I think it would be more natural to set the parent ee element to the global environment:
> parent.env(ee) <- globalenv() > with(ee, a - b) [1] -1 a and b will always be found in ee , since this is the first definition environment encountered, but functions can be searched in the usual place, as if it were executed on the command line. If you do this in a function call, you need to assign the correct environment.