开发者

"$<-" and environments

Why doesn't the following work? Ie, why doesn't calling "$<-" on an environment have a visible effect outside of the function?

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

And also

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

Whereas, if we do this at the top l开发者_运维知识库evel:

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

Thanks!


It does have an effect, just not the one you're looking for!

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

The reason is that $<- evaluates its second argument in a non-standard way (as it must, to get x instead of eval(x) in e$x <- 1, if that makes any sense. Try env[[name]] <- value

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜