3

I'm trying to test that two vectors are equal using both all and all.equal but they give different results and I'm not sure why.

> x = seq(0,1,by=0.2)
> x
[1] 0.0 0.2 0.4 0.6 0.8 1.0
 > y = c(0.0, 0.2, 0.4, 0.6, 0.8, 1.0)
> all(x == y)
[1]  FALSE
> all.equal(x, y)
[1] TRUE
cosmosa
  • 743
  • 1
  • 10
  • 23

1 Answers1

5

It looks like you've fallen into the first circle of R hell, where floating point numbers don't behave as expected.

The misbehaving pair is x[4] & y[4] (as per coffeeinjunky's comment above). Look at them closely:

> print(c(x[4], y[4]))
[1] 0.6 0.6
> print(c(x[4], y[4]), digits = 16)
[1] 0.6000000000000001 0.6000000000000000

all.equal has a default tolerance level around 1.5e-8, & differences below this threshold are not reported. This is why all.equal(x, y) returns TRUE, while all(x==y) returns FALSE.

This post discusses the issue in more detail: Numeric comparison difficulty in R

Z.Lin
  • 28,055
  • 6
  • 54
  • 94