0

I've got a strange result for my modulo query here. Maybe somebody has a solution for it:

d  <- seq(0.0,1.0,0.1)
lab.y <- ifelse(((d*10) %% 2.0 == 0.0),d, NA)

will give the result:

 [1] 0.0  NA 0.2  NA 0.4  NA  NA  NA 0.8  NA 1.0

so the 0.6 is missing.

I tried to add a query like:

ifelse((d*10/2 == 3.0), d, NA)

which is all FALSE even though

d*10/2
[1] 0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0

... I don't really understand what's going on here.

Thanks a lot in advance!

M. Weeker
  • 140
  • 2
  • 10

1 Answers1

1

This is due to floating point errors, you should look for low absolute differences instead of exact matches. It is not 0.6, but (just an example) 0.6000000003 or 0.5999999997. Try something like:

ifelse((abs((d*10) %% 2)<0.000001), d, NA)
ElGavilan
  • 6,610
  • 16
  • 27
  • 36
Jan van der Vegt
  • 1,471
  • 12
  • 34