R函数返回满足最小和最大范围的矩阵行

时间:2022-09-26 12:40:00

Having the following matrix:

有以下矩阵:

      [,1] [,2] [,3] [,4] 
  [1,]  231   14  517  310 
  [2,]    1  154   18   21 
  [3,]  121    6  198   23 

I want to get only the rows that have a minimum range for each row between 2 and 30.

我想只获得2到30之间每行最小范围的行。

Min range for each row:

每行的最小范围:

 [1] 79
 [2]  3
 [3] 17

so we get only [2] and [3]

所以我们只得到[2]和[3]

and a max range between 0 and 160 Max range for each row:

并且每行的最大范围在0到160之间:

  [1] 503
  [2] 153
  [3] 192

so finally we get only [2] that satisfies the two conditions. Can you please provide an R language function which can generate this result?

所以最后我们只得到满足这两个条件的[2]。能否请您提供可以生成此结果的R语言功能?

Regards, Dimitris

2 个解决方案

#1


2  

Setting up the data

设置数据

m <- read.table(text="231   14  517  310
                        1  154   18   21
                      121    6  198   23")

m <- as.matrix(m)

Maximum range of each row

每行的最大范围

maxr <- apply(m, 1, function(x) diff(range(x)))

Minimum range of each row

每行的最小范围

minr <- apply(m, 1, function(x) min(diff(sort(x))))

Stringing it together into a condition on rows

将它们串在一起成为行上的条件

m[minr > 2 & minr < 20 & maxr > 0 & maxr < 160, ]
#   1 154  18  21 

#2


2  

Here is a solution using the function dist():

这是一个使用函数dist()的解决方案:

m <- matrix(
  c(231, 14, 517, 310, 
    1,  154,   18,   21, 
  121,    6,  198,   23 ), 3, byrow=TRUE)


mi <- apply(m, 1, function(x) min(dist(x)))
ma <- apply(m, 1, function(x) max(dist(x)))

m[mi > 2 & mi < 30 & ma > 0 & ma < 160, ]

#1


2  

Setting up the data

设置数据

m <- read.table(text="231   14  517  310
                        1  154   18   21
                      121    6  198   23")

m <- as.matrix(m)

Maximum range of each row

每行的最大范围

maxr <- apply(m, 1, function(x) diff(range(x)))

Minimum range of each row

每行的最小范围

minr <- apply(m, 1, function(x) min(diff(sort(x))))

Stringing it together into a condition on rows

将它们串在一起成为行上的条件

m[minr > 2 & minr < 20 & maxr > 0 & maxr < 160, ]
#   1 154  18  21 

#2


2  

Here is a solution using the function dist():

这是一个使用函数dist()的解决方案:

m <- matrix(
  c(231, 14, 517, 310, 
    1,  154,   18,   21, 
  121,    6,  198,   23 ), 3, byrow=TRUE)


mi <- apply(m, 1, function(x) min(dist(x)))
ma <- apply(m, 1, function(x) max(dist(x)))

m[mi > 2 & mi < 30 & ma > 0 & ma < 160, ]