Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter a data frame by row values but with tolerance

Tags:

r

df <- data.frame(x = c(6.00001, 6.00000, 5.99999, 5, 2), y = c(1, 2, 3, 4, 5))

        x y
1 6.00001 1
2 6.00000 2
3 5.99999 3
4 5.00000 4
5 2.00000 5

I can use df[df$x == 6,] to quickly return the rows that has x == 6,

  x y
2 6 2

but what if I want to have a tolerance here? all.equal seems not applicable here:

df[all.equal(df$x, 6, 0.0001), ]
    x  y
NA NA NA

If I want to find the rows that x are very close to 6, is there a short way to do it? Expected output:

        x y
1 6.00001 1
2 6.00000 2
3 5.99999 3
like image 494
Tianjian Qin Avatar asked Nov 19 '25 17:11

Tianjian Qin


1 Answers

You can use near(), which is a wrapper for abs(x - y) < tol:

library(dplyr)

df %>%
  filter(near(x, 6, tol = 1e-04))

        x y
1 6.00001 1
2 6.00000 2
3 5.99999 3
like image 56
Ritchie Sacramento Avatar answered Nov 21 '25 05:11

Ritchie Sacramento