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

David Winsemius dwinsemius at comcast.net
Tue May 7 21:20:38 CEST 2013


On May 7, 2013, at 11:52 AM, Mark Coletti wrote:

> On Tue, May 7, 2013 at 4:53 AM, peter dalgaard <pdalgd at gmail.com> wrote:
> 
>> 
>> 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.
>> 
>> 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
> 
> 
> I apologize for not being clearer with my question.  Regardless, you were
> able to suss out what I wanted -- using a vector of y coordinates to pull
> individual elements out by column from a matrix.  Your use of cbind() to
> effect this works.
> 
> And using cbind() to extract matrix elements in that way is very
> non-intuitive.  There is no way I would have thought of that on my own.

So read ?Extract more carefully.

It's a very important help page and failing to read it (ideally least 5 times)  results in many, many questions on this list.

-- 

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list