[R] Matrix indexes

Prof Brian Ripley ripley at stats.ox.ac.uk
Mon Jan 12 11:17:03 CET 2004


On Mon, 12 Jan 2004, W. Beldman wrote:

> Two questions about matrix indexing:

Not about `matrix indexing', which may have confused you.  Matrix indexing
of a matrix is when the index is a two-column matrix of row-column number
pairs.

> Is is correct that   V <- V[lower.tri(V, diag=TRUE)]   returns the lower 
> triangular of matrix V, that is: all elements above diagonal are set to zero? I 

No, omitted.

> understand that the triangle of matrix elements of V for which lower.tri is 
> TRUE are returned while the others (above diagonal) are set to zero (or NA ???).

So this is vector indexing by a logical vector.  It does no harm to try 
it:

> V <- matrix(1:16, 4,4)
> V
     [,1] [,2] [,3] [,4]
[1,]    1    5    9   13
[2,]    2    6   10   14
[3,]    3    7   11   15
[4,]    4    8   12   16
> lower.tri(V, diag=TRUE)
     [,1]  [,2]  [,3]  [,4]
[1,] TRUE FALSE FALSE FALSE
[2,] TRUE  TRUE FALSE FALSE
[3,] TRUE  TRUE  TRUE FALSE
[4,] TRUE  TRUE  TRUE  TRUE
> V[lower.tri(V, diag=TRUE)]
 [1]  1  2  3  4  6  7  8 11 12 16

so the result is the lower triangle read out as a vector in the usual
first-index-varies fastest order.

> If D and B are vectors of logicals,
> what does  V  contain after   V <- v[D, B, drop=FALSE]   ?
> I guess that elements are returned if both indexes D and B are TRUE, but I'm 
> not really convinced... (And again, what about the other elements?)

Yes. Again, simple example:

> B <- c(T, F, T, F)
> D <- c(T, T, F, F)
> outer(B, D)
     [,1] [,2] [,3] [,4]
[1,]    1    1    0    0
[2,]    0    0    0    0
[3,]    1    1    0    0
[4,]    0    0    0    0
> V[B, D]
     [,1] [,2]
[1,]    1    5
[2,]    3    7


And finally an example of matrix indexing

> U <- matrix(c(1,1,2,3), 2, 2, byrow=T)
> U
     [,1] [,2]
[1,]    1    1
[2,]    2    3
> V[U]
[1]  1 10


> These are probably tutorial questions, but I'm still not sure after reading "R 
> Language Definition (draft): Evaluation of expressions" and applicable sections 
> of "The R Reference Manual". Thanx!

Some of the books in the FAQ, notably `S Programming', will help a lot.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list