Search code examples
rmatrixfiltermaxmin

Filter matrix in R according to difference between maximum and minimum values in rows


I have a matrix A like:

 1   2   3   4   5
 2   3   6   4   3
 3   3   3   3   4
 2   3   3   3   4 

I want to get only the rows where the difference between the maximum and minimum value in a row is larger than 2.

The function should return this matrix:

 1   2   3   4   5
 2   3   6   4   3

Solution

  • You can get the difference between min and max with range and diff and select rows where it is greater than 2.

    A[apply(A, 1, function(x) diff(range(x))) > 2, ]
    
    #     [,1] [,2] [,3] [,4] [,5]
    #[1,]    1    2    3    4    5
    #[2,]    2    3    6    4    3
    

    For larger matrices you can also use rowRanges function from matrixStats.

    mat <- matrixStats::rowRanges(A)
    A[mat[, 2] - mat[, 1] > 2, ]