[R] match rows of R

Berend Hasselman bhh at xs4all.nl
Wed Jun 26 11:13:52 CEST 2013


On 26-06-2013, at 10:30, Yuliya Matveyeva <yuliya.rmail at gmail.com> wrote:

> I suggest using vectorization :
> 
> find_row <- function(m,v) { which(!(abs(rowSums(m - rep(v, each = nrow(m)))
> )) > 0) }
> 
> The function matroweqv mentioned above would give any row with the first
> element equal to the first element in vector v.

Correct.
This version should be better

matroweqv <- function(m,v) {
    z <- which(t(m)==v, arr.ind=TRUE,useNames=FALSE)
    if(dim(z)[1]==0) return(NA) else if(all(z[,2]==z[1,2])) return(z[1,2])  else return(NA)
}                     

Instead of NA one could also return -1 if no row equals the vector.

Berend


> The function find_row matches each row of the matrix as a whole to the
> vector v.
> 
> 
> 2013/6/26 Sachinthaka Abeywardana <sachin.abeywardana at gmail.com>
> 
>> Hi all,
>> 
>> What would be an efficient way to match rows of a matrix to a vector?
>> 
>> ex:
>> 
>> m<-matrix(1:9, nrow=3)
>> 
>> m     [,1] [,2] [,3]
>> [1,]    1    4    7
>> [2,]    2    5    8
>> [3,]    3    6    9
>> 
>> #################################
>> which(m==c(2,5,8))        # I want this to return 2
>> ######################
>> 
>> Thanks,
>> Sachin
>> 
>>        [[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.
>> 
> 
> 
> 
> -- 
> Sincerely yours,
> Yulia Matveyeva,
> Department of Statistical Modelling,
> Faculty of Mathematics and Mechanics,
> St Petersburg State University, Russia
> 
> 	[[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