[R] effective matrix subset

Marc Schwartz marc_schwartz at comcast.net
Sat Aug 9 13:29:59 CEST 2008


on 08/09/2008 06:01 AM jgarcia at ija.csic.es wrote:
> Hi;
> If we have a matrix A, and a vector X, where length(X)=nrow(A), and X
> contains a wanted column for each row in A, in row ascending order. How
> would be the most effective way to extract the desired vector V (with
> length(V)=nrow(A))?


A <- matrix(1:20, 4, 5)

 > A
      [,1] [,2] [,3] [,4] [,5]
[1,]    1    5    9   13   17
[2,]    2    6   10   14   18
[3,]    3    7   11   15   19
[4,]    4    8   12   16   20


# Create an arbitrary set of indices, one for each row in A
X <- c(2, 5, 1, 4)

 > X
[1] 2 5 1 4


Presumably you want:

V <- c(A[1, 2], A[2, 5], A[3, 1], A[4, 4])

 > V
[1]  5 18  3 16


If so, then:

 > sapply(seq(nrow(A)), function(i) A[i, X[i]])
[1]  5 18  3 16


Is that what you were looking for?


BTW, see ?diag for a special case:

 > diag(A)
[1]  1  6 11 16


HTH,

Marc Schwartz



More information about the R-help mailing list