Reputation: 191
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.
Min range for each row:
[1] 79
[2] 3
[3] 17
so we get only [2] and [3]
and a max range between 0 and 160 Max range for each row:
[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?
Regards, Dimitris
Upvotes: 0
Views: 121
Reputation: 12559
Here is a solution using the function 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, ]
Upvotes: 2
Reputation: 8846
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
Upvotes: 2