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

其他-根据行中最大值和最小值之间的差过滤R中的矩阵

(其他 - Filter matrix in R according to difference between maximum and minimum values in rows)

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

我有一个矩阵A像:

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

我只想获取一行中最大值和最小值之间的差异大于2的行。

该函数应返回以下矩阵:

 1   2   3   4   5
 2   3   6   4   3
Questioner
Kelvin Tan
Viewed
0
Ronak Shah 2020-12-02 16:53:59

你可以使用range来获得最小值和最大值之间的差异diff并选择大于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

对于更大的矩阵,你还可以使用中的rowRanges函数matrixStats

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