[R] Finding Equal Elements in Vectors

Marc Schwartz MSchwartz at MedAnalytics.com
Sun Feb 27 16:50:07 CET 2005


After I hit send, I realized an error in:

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

The above should be:

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

They happen to be the same by coincidence only, given the values that I
used.

The first syntax returns the _indices_ of the matches, not the actual
matched values themselves. Important difference.

For example and clarity:

> a <- 5:15
> b <- 12:20

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

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

> a[which(a %in% b)]
[1] 12 13 14 15

Sorry for the confusion.

Marc




More information about the R-help mailing list