[Rd] treatment of zero and negative elements in matrix indices

From: Tony Plate <tplate_at_blackmesacapital.com>
Date: Fri 15 Apr 2005 - 15:54:37 GMT


Matrix indexing seems to give rather "variable" results when zeros or negative values are included among the indices (in terms of both error messages and in terms of the number of returned values when there is no error message).

Is this the intended behavior?

I couldn't see any comments about zeros or negative values in matrix indices in either ?"[" or Section 3.4.2 "Indexing matrices and arrays" of the "R Language Definition" (Version 2.0.1), or in Section 5.3 "Index arrays" of "An Introduction to R" (Version 2.1.0).

(It looks like the special treatment of zeros and negative indices is being applied to the vector indices after they are derived by standard indexing arithmetic from the matrix indices -- so zeros and negative values in the matrix indices have no special meaning. There does seem to be some range checking, but it's not consistent -- sometimes index values that are out of range get through.)

> x <- matrix(1:6,ncol=2)
> dim(x)

[1] 3 2
> x

      [,1] [,2]

[1,]    1    4
[2,]    2    5
[3,]    3    6

> x[rbind(c(1,1), c(2,2))]

[1] 1 5
> x[rbind(c(1,1), c(2,2), c(0,1))]

[1] 1 5
> x[rbind(c(1,1), c(2,2), c(0,0))]

Error: only 0's may mix with negative subscripts
> x[rbind(c(1,1), c(2,2), c(0,2))]

[1] 1 5 3
> x[rbind(c(1,1), c(2,2), c(0,3))]

Error: subscript out of bounds
> x[rbind(c(1,1), c(2,2), c(1,0))]

Error: only 0's may mix with negative subscripts
> x[rbind(c(1,1), c(2,2), c(2,0))]

Error: only 0's may mix with negative subscripts
> x[rbind(c(1,1), c(2,2), c(3,0))]

[1] 1 5
> x[rbind(c(1,1), c(2,2), c(1,2))]

[1] 1 5 4
> x[rbind(c(1,1), c(2,2), c(-1,2))]

[1] 1 5 2
> x[rbind(c(1,1), c(2,2), c(-2,2))]

[1] 1 5 1
> x[rbind(c(1,1), c(2,2), c(-3,2))]

[1] 1 5
> x[rbind(c(1,1), c(2,2), c(-4,2))]

Error: only 0's may mix with negative subscripts
> x[rbind(c(1,1), c(2,2), c(-1,-1))]

Error: subscript out of bounds
>
> # range checks are at least sometimes not applied
> x <- matrix(1:6, ncol=3)
> dim(x)

[1] 2 3
> x[rbind(c(1,1), c(2,2), c(-3,3))]

[1] 1 4 1
> x[rbind(c(1,1), c(2,2), c(-4,3))]

[1] 1 4
>

> version

          _
platform i386-pc-mingw32

arch     i386
os       mingw32

system i386, mingw32
status
major 2
minor 0.1
year 2004
month 11
day 15
language R
>

(I see the same behavior in R 2.1.0 beta of 2005/04/04)

PS: FWIW, S-PLUS 6.2 does something more like one would get when using each row of the index matrix as arguments to a call to "[", except that negative values are not allowed at all (any zero value in a row causes that row to be omitted from the result).



R-devel@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel Received on Sat Apr 16 01:59:01 2005

This archive was generated by hypermail 2.1.8 : Mon 20 Feb 2006 - 03:21:03 GMT