[R] Getting indeices of intersecting elements.

William Dunlap wdunlap at tibco.com
Wed Oct 14 19:28:09 CEST 2009


> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Praveen Surendran
> Sent: Wednesday, October 14, 2009 9:15 AM
> To: r-help at r-project.org
> Subject: [R] Getting indeices of intersecting elements.
> 
> Hi,
>
> Is there a command to get the indices of intersecting elements of two
> vectors as intersect() will give the elements and not its indices.   

intersect() uses match() to do that.

match(x,y,nomatch) gives the indices of elements of y that
elements of x match and match(y,x,nomatch) gives
the indices of the elements of x that elements of
y match.  In each case, the unmatched elements
are marked by the value in nomatch.  E.g.

   > x<-letters[1:5]
   > y<-letters[(1:5)*2]
   > x
   [1] "a" "b" "c" "d" "e"
   > y
   [1] "b" "d" "f" "h" "j"
   > match(y,x,nomatch=0) # x[c(2,4)] are in y
   [1] 2 4 0 0 0
   > match(x,y,nomatch=0) # y[c(1,2)] are in x
   [1] 0 1 0 2 0

(If the second argument contains duplicates the index
is for the first of them.)

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com 

> Thanks in advance.
> 
>  
> 
> Praveen Surendran
> 
> School of Medicine and Medical Sciences
> 
> University College Dublin
> 
> Belfield, Dublin 4
> 
> Ireland.
> 
> 
> 	[[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