[R] Finding Equal Elements in Vectors

Marc Schwartz MSchwartz at MedAnalytics.com
Sun Feb 27 17:38:32 CET 2005


On Sun, 2005-02-27 at 09:50 -0600, Marc Schwartz wrote:

[snip]

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

One more time:

The above can be simplified to just:

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


Also, if you happen to be comparing floating point numbers in the two
vectors, consider that floating point comparisons are inexact due to the
way in which floats are represented in binary on computers.

For example:

> a <- seq(0, 1.5, 0.1)
> b <- seq(1.0, 1.5, 0.1)

> a
 [1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 1.1 1.2 1.3 1.4 1.5
> b
[1] 1.0 1.1 1.2 1.3 1.4 1.5

> a[a %in% b]
[1] 1.0 1.1 1.3 1.5

Note that in the above, 1.2 and 1.4 are not returned as a result of
attempting an exact comparison of these two floating point numbers.

Using something like:

> a[round(a, 1) %in% round(b, 1)]
[1] 1.0 1.1 1.2 1.3 1.4 1.5

will work, since we are rounding the floats to one decimal place prior
to the comparison.


Marc
<Going for another cup of coffee...>




More information about the R-help mailing list