user8102905 user8102905 - 5 months ago 30
R Question

Filter matrix rows where row numbers have max difference between them

Having a matrix A like:

1 21 3 49 59
21 33 59 67 65
3 5 7 8 11
21 76 5 4 9


I want to get only the rows where there are no 3 or more numbers per row all having between them max difference < 10

this function should return only Row 1.

Answer Source

You cun find the diff of all combinations of values, and use rowSums to filter, i.e.

A[rowSums(t(apply(A, 1, function(i)combn(i, 2, diff))) < 10) < 3,]
#[1]  1 21  3 49 59