choose rows in which the absolute value of subtraction is less a specified value

We can get the difference between the ‘X1’, ‘X2’ columns, create a logical expression in subset to subset the rows

subset(dataset, abs(X1 - X2) >= 2)
#  ID X1 X2
#3  3  3  1
#4  4  4  1
#6  6  6 20
#7  7  7 20
#8  8  9 20
#9  9 10 20

Or using index

subset(dataset, abs(dataset[[2]] - dataset[[3]]) >= 2)

data

dataset <- structure(list(ID = 1:9, X1 = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 9L, 
10L), X2 = c(2L, 1L, 1L, 1L, 5L, 20L, 20L, 20L, 20L)),
class = "data.frame", row.names = c(NA, 
-9L))

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top