[R] match rows of R

arun smartpink111 at yahoo.com
Wed Jun 26 21:44:40 CEST 2013


This might also work:

roweqv2<- function(m,v){indx<-1+Reduce("+",lapply(seq_len(ncol(m)),function(i) (2^i)*(m[,i]==v[i])))
             which(indx==max(indx))}    

roweqv2(m,v)
#[1] 2
 system.time(res2<-roweqv2(m1,v1))
#   user  system elapsed 
  #0.008   0.000   0.008 
 identical(res,res2)
#[1] TRUE

#On a bigger dataset


set.seed(248)
 m1<-matrix(sample(1:15,3e7,replace=TRUE),ncol=3)
 v1<- c(10,12,4)
 system.time(res<- roweqv(m1,v1))
#   user  system elapsed 
# 12.404   1.248  13.677 
  system.time(res2<-roweqv2(m1,v1))
#   user  system elapsed 
 # 0.760   0.312   1.076 

identical(res,res2)
#[1] TRUE


A.K.



----- Original Message -----
From: arun <smartpink111 at yahoo.com>
To: Sachinthaka Abeywardana <sachin.abeywardana at gmail.com>
Cc: R help <r-help at r-project.org>
Sent: Wednesday, June 26, 2013 3:26 PM
Subject: Re: [R] match rows of R

Hi,
Try:
 roweqv<- function(m,v) which(!is.na(match(interaction(as.data.frame(m),drop=TRUE),paste(v,collapse="."))))
v<- c(2,5,8)
roweqv(m,v)
#[1] 2


set.seed(24)
m1<-matrix(sample(1:15,3e5,replace=TRUE),ncol=3)
v1<- c(10,12,4)

 system.time(res<- roweqv(m1,v1))
  # user  system elapsed 
  #0.132   0.000   0.130 
res
# [1]     5   381  2760  3793  9667 16881 18866 21219 24961 36220 38366 54382
#[13] 54951 55825 57167 67636 70713 71087 73284 82797 83255 85748 86216 86690
#[25] 93120 95399 96370

head(m1[res,])
#     [,1] [,2] [,3]
#[1,]   10   12    4
#[2,]   10   12    4
#[3,]   10   12    4
#[4,]   10   12    4
#[5,]   10   12    4
#[6,]   10   12    4

v2<- c(20,5,4)
roweqv(m1,v2)
#integer(0)

A.K.
----- Original Message -----
From: Sachinthaka Abeywardana <sachin.abeywardana at gmail.com>
To: "r-help at r-project.org" <r-help at r-project.org>
Cc: 
Sent: Wednesday, June 26, 2013 4:03 AM
Subject: [R] match rows of R

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.




More information about the R-help mailing list