[R] select element from each row of the matrix

Peter Alspach Peter.Alspach at plantandfood.co.nz
Wed Jul 20 22:35:37 CEST 2011


Tena koe

Assuming your matrix is called yourMatrix, then try

apply(yourMatrix, 1, function(x) which(x<=5))

HTH ...

Peter Alspach

> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of gallon li
> Sent: Thursday, 21 July 2011 8:23 a.m.
> To: R-help at r-project.org
> Subject: [R] select element from each row of the matrix
> 
> I have a 5 column matrix like
> 
> 12 10 8 6 3
> 10 9 8 7 5
> 14 NA 4 NA NA NA
> 15 NA 10 NA 5
> ...
> 
> I want to select the position of the first entry for each row <=5
> 
> for example, for the first row, I want to select the last element and
> return
> its position as 5;
> for th e third row, I want to select the third element and return its
> position as 3;
> similarly for the 4th row, I want to select the fifth element and
> return its
> position 5.
> 
> I am wondering how to do this fast? Thanks a lot!
> 
> 	[[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.

The contents of this e-mail are confidential and may be subject to legal privilege.
 If you are not the intended recipient you must not use, disseminate, distribute or
 reproduce all or any part of this e-mail or attachments.  If you have received this
 e-mail in error, please notify the sender and delete all material pertaining to this
 e-mail.  Any opinion or views expressed in this e-mail are those of the individual
 sender and may not represent those of The New Zealand Institute for Plant and
 Food Research Limited.



More information about the R-help mailing list