[R] Finding Equal Elements in Vectors

Marc Schwartz MSchwartz at MedAnalytics.com
Sun Feb 27 16:24:54 CET 2005


On Sun, 2005-02-27 at 16:07 +0100, Sven C. Koehler wrote:
> Hello!
> 
> I have two vectors and want to know how many of their elements are
> equal - 
> what's the best way to do this in R?  
> 
> Best regards,
> 
> Sven

> a <- 1:10
> b <- 8:20

> a
 [1]  1  2  3  4  5  6  7  8  9 10
> b
 [1]  8  9 10 11 12 13 14 15 16 17 18 19 20


If you just want to know how many elements in 'a' are in 'b':

> sum(a %in% b)
[1] 3

If you want to know which elements in 'a' are in 'b':

> which(a %in% b)
[1]  8  9 10

See ?"%in%" and ?which for more information.

HTH,

Marc Schwartz




More information about the R-help mailing list