[R] elements in a matrix to a vector

Ray Brownrigg ray at mcs.vuw.ac.nz
Wed Nov 9 20:33:31 CET 2005


> my apologies to everyone taking the time to answer this question.  i
> didn't explain myself very well.  
> 
> i have the indices of the elements of the matrix and the matrix won't
> necessarily have zeros everywhere else.  is there a way to use the
> indices to strip the elements i need?
> 
RTFM ?"[".

> x <- matrix(c(0, 2, 0, 0, 0, 4, 3, 0, 0), nrow=3)
> x
     [,1] [,2] [,3]
[1,]    0    0    3
[2,]    2    0    0
[3,]    0    4    0
> ?"["
> xx <- matrix(c(1, 2, 3, 3, 1, 2), ncol=2)
> xx
     [,1] [,2]
[1,]    1    3
[2,]    2    1
[3,]    3    2
> x[xx]
[1] 3 2 4
>                                       

HTH,
Ray




More information about the R-help mailing list