"$ <-" and environments

Why does the following not work? That is, why calling "$ <-" in the environment has a visible effect outside the function?

myAssign <- function(env, name, value) {
  "$<-"(env, name, value)
}
e <- new.env()
myAssign(e, "x", 1)
e$x  # NULL

And

myAssign(e, "x", 1)$x  # NULL

If we do this at the top level:

"$<-"(e, "x", 1)
e$x  # 1

Thank!

+3
source share
1 answer

It has the effect, not the one you are looking for!

> myAssign(e, "x", 1)
<environment: 0x1dcd198>
> ls(e)
[1] "name"

The reason is that it $<-evaluates its second argument in a non-standard way (as it should be to get xinstead of eval(x)c e$x <- 1), if that makes sense. Tryenv[[name]] <- value

+7
source

All Articles