[R] Extracting elements from a matrix using a vector containing indices

peter dalgaard pdalgd at gmail.com
Tue May 7 10:53:48 CEST 2013


On May 7, 2013, at 06:39 , Mark Coletti wrote:

> I have a matrix of data that has a corresponding vector of indices.  I
> would like to use those indices to extract specific matrix elements into a
> new vector.  In other words, I have an R X C matrix with a corresponding
> vector of C elements that have numbers mapping into specific elements of
> the matrix.  I'd like to generate a new vector C long that contains those
> elements.
> 
> My first approach is to iteratively grind through each matrix column to
> manually extract the element corresponding to that column as referenced by
> the appropriate index, and then appending that to a vector.  However, my R
> instincts are that any time one has to craft a for loop to do something in
> R that you are very likely Doing It Wrong; there's probably a very simple
> one liner in R that will do all that that for loop would do.
> 
> I know there must be a simple "R way" to do this, but I remain flummoxed on
> how to do so.  I've been feebly poking at the plyr package's maplyr() and
> colwise() since I have a matrix and want to extract an array from it, and
> this is inherently a column wise operation, so ... hmm.
> 
> Should I just give up and use a for loop?


As Berend says, you're not specifying the problem very clearly. Are you looking for something like this (indexing with a matrix)?

> M <- matrix(round(rnorm(20,20,10)),4,5)
> M
     [,1] [,2] [,3] [,4] [,5]
[1,]   29   19   18   13    0
[2,]   24   24   11   25   10
[3,]   20    9   12   11   24
[4,]   28    3   16   17   32
> Ix <- sample(1:4,5,replace=TRUE)
> Ix
[1] 3 2 2 4 3
> M[cbind(Ix,1:5)]
[1] 20 24 11 17 24


-- 
Peter Dalgaard, Professor
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list