[R] Overlapping assignment
Rob Steele
rfin.20.phftt at xoxy.net
Tue Apr 25 15:49:39 CEST 2006
Prof Brian Ripley wrote:
> On Mon, 24 Apr 2006, Rob Steele wrote:
>
>> Is it valid to assign a slice of an array or vector to an overlapping
>> slice of the same object? R seems to do the right thing but I can't
>> find anything where it promises to.
>
> Yes. Remember R is a vector language, so it is not doing this
> index-by-index. Also, what you are doing is
>
> a <- `[<-`(a, 4:12, 1:9)
>
> which should make this easier to understand: you get a new object, and you
> don't expect
>
> x <- x^2
>
> to be a problem, do you?
>
>>> a <- 1:12
>>> a[4:12] <- a[1:9]
>>> a
>> [1] 1 2 3 1 2 3 4 5 6 7 8 9
>>
>>> b <- 1:12
>>> b[1:9] <- b[4:12]
>>> b
>> [1] 4 5 6 7 8 9 10 11 12 10 11 12
>>
Thank you very much. I understand that '[<-' is a function that
produces a new "a" but I don't see that it necessarily follows that
overlapping assignment is valid. Even if R worked index-by-index (which
at some level it must be doing) x <- x^2 would behave as expected.
It seems to me that R must either be smart about whether to copy left to
right or right to left or else must copy the original object and then
perform the destination indexing on the copy and the source indexing on
the original. Either way would keep it from overwriting a cell before
it has a chance to copy it to its new location. And if R does it by
being smart about left and right, how does it handle index vectors that
are out of order? For example:
> a <- 1:12
> a[12:4] <- a[9:1]
> a
[1] 1 2 3 1 2 3 4 5 6 7 8 9
It looks like it must be working with both the original and the copy
during the assignment.
More information about the R-help
mailing list