I would be surprised if it were not a duplicate, but I could not find a solution.
I understand the limitations of == to check if floating point numbers are equal. Need to use all.equal
0.1 + 0.2 == 0.3 # FALSE all.equal(0.1 + 0.2, 0.3) # TRUE
But == has the advantage of being vectorized:
set.seed(1) Df <- data.frame(x = sample(seq(-1, 1, by = 0.1), size = 100, replace = TRUE), y = 0.1) Df[Df$x > 0 & Df$x < 0.2,]
I can write the (bad) function myself:
All.Equal <- function(x, y){ stopifnot(length(x) == length(y)) out <- logical(length(x)) for (i in seq_along(x)){ out[i] <- isTRUE(all.equal(x[i], y[i])) } out } sum(All.Equal(Df$x, Df$y))
which gives the correct answer, but still has a long way to go.
microbenchmark::microbenchmark(All.Equal(Df$x, Df$y), Df$x == Df$y) Unit: microseconds expr min lq mean median uq max neval cld All.Equal(Df$x, Df$y) 9954.986 10298.127 20382.24436 10511.5360 10798.841 915182.911 100 b Df$x == Df$y 16.857 19.265 29.06261 30.8535 38.529 45.151 100 a
Another option could be:
All.equal.abs <- function(x,y){ tol <- .Machine$double.eps ^ 0.5 abs(x - y) < tol }
which performs a comparison with == .
What is an existing function that performs this task?