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

Berend Hasselman bhh at xs4all.nl
Tue May 7 06:53:39 CEST 2013


On 07-05-2013, at 06:39, Mark Coletti <mcoletti at gmail.com> 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.
> 

It's not clear what you want.
The vector C contains row numbers or column numbers?

> 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.

So you want to extract a single element from each column?
Your matrix is Mat and the vector is called vec

Mat[vec,]

should do it.

If this is not what you want you will have to be more specific.

Berend

>  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?
> -- 
> mcoletti at gmail.com
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> 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