[R] effective matrix subset

Dan Davison davison at stats.ox.ac.uk
Sat Aug 9 13:52:53 CEST 2008


On Sat, Aug 09, 2008 at 06:29:59AM -0500, Marc Schwartz wrote:
> 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

Or

> A[cbind(seq(nrow(A)), X)]
[1]  5 18  3 16

Dan

>
>
> Is that what you were looking for?
>
>
> BTW, see ?diag for a special case:
>
> > diag(A)
> [1]  1  6 11 16
>
>
> HTH,
>
> Marc Schwartz
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list