[R] I don't understand this
tlumley at u.washington.edu
Wed Sep 3 16:21:59 CEST 2003
On Wed, 3 Sep 2003, Richard A. O'Keefe wrote:
> Another assignment-related thing I'm not clear on is what
> f(x) <<- e
> is supposed to do.
> f(x) <- e
> is equivalent to
> x <- "f<-"(x, value=e)
> x <<- e
> assigns to x in the next outer environment,
> but a simple macro-expansion of
> f(x) <<- e
> x <<- "f<-"(x, value=e)
> may have the nasty effect of writing to an outer x a value derived from
> an inner one.
> Now, that seems to be exactly what happens in R:
> > x <- c(1,2,3)
> > f <- function(x) x <<- x
> > f(77)
> > x
>  77 77
> While the documentation and source code _could_ tell me whether this
> is intentional, as far as I can tell (and I have, needless to say,
> looked) they _don't_.
I'm fairly confident that this is a case where there was no intention one
way or the other.
> Now, despite its misleading opening screen (which says that the
> target of an assignment is "a variable name (possibly quoted)",
> ?"<<-" goes on to say that
> In all the assignment operator expressions, `x' can be a name or
> an expression defining a part of an object to be replaced (e.g.,
> `z[]'). The name does not need to be quoted, though it can be.
> (the arrows are my emphasis.) So it's explict that f(x) <<- e is
> *supposed* to be allowed and I don't need to ask about that.
Well, it's possible that the documentation is wrong.
> The question is, what is f(x) <<- e supposed to do when there is an
> x in the current environment as well as one in an outer environment?
> It doesn't make much sense to fetch from one variable and store into
> the other, but that's what R actually does. Is that really what's
> *supposed* to happen?
I don't think so. <<- works as intended for subscripting of relatively
simple objects, but has the result you describe even for [.data.frame.
I think it's a bug.
More information about the R-help