Q:

Why is R filtering not working for specific values?

I am struggling to understand why my R is behaving in a certain way. I've created a simple example below to show the issue.
x <- seq(0,2,0.05)
y <- seq(1,length(x))

z <- data.frame(x,y)

Now that the data frame z has been created, I am going to try filter for some values.
This first piece of code works exactly as expected:
z[z$x==1,]

   x  y
21 1 21

However the following doesn't work as expected:
z[z$x==1.2,]

x y
<0 rows> (or 0-length row.names)

Does anybody know why this is happening? The value 1.2 definitely exists in column x.

A:

This is due to tiny differences in the underlying floating point representation of the numbers in R. Look:
z[abs(z$x - 1.2) < 0.0000001,]
#>      x  y
#> 25 1.2 25

If you create the same sequence by dividing integers rather than sequentially adding 0.05 (which cannot be exactly represented in floating point) the equality now works:
x <- 0:40 / 20
which(x == 1.2)
#> [1] 25

