[R] effective matrix subset

Marc Schwartz
Sat, 09 Aug 2008 11:29:59 -0000

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