[R] Superassignment (<<-) and indexing

Thomas Lumley tlumley at u.washington.edu
Sat Sep 3 00:16:17 CEST 2005

On Fri, 2 Sep 2005, Brahm, David wrote:

> In a clean environment under R-2.1.0 on Linux:
>> x <- 1:5
>> x[3] <<- 9
> Error: Object "x" not found
> Isn't that odd?  (Note x <<- 9 works just fine.)

Well, yes and no.

It is the result of a bug fix a version or two ago that dealt with the 
case where there was a local variable with the same name as a 
variable being modified by a complex superassignment.

As the R language definition now explains
   x[3] <<- 9
is short for
   `*tmp*` <- get(x, envir=parent.env, inherits=TRUE)
   `*tmp*`[3] <- 9
   x <<- `*tmp*`

and so it doesn't work if x doesn't exist in the parent environment.

x <<- 9
is ok, since it doesn't have to look up x before assigning it, but it is 
still a wart that x<<-9 creates a local variable x when executed in the 
global environment but not when executed anywhere else.


More information about the R-help mailing list