Warm tip: This article is reproduced from serverfault.com, please click

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

发布于 2020-12-02 08:49:35

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
Questioner
Kelvin Tan
Viewed
0
Ronak Shah 2020-12-02 16:53:59

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, ]