user8102905
user8102905

Reputation: 191

Calculate the max and the min difference between two adjacent numbers

Having a matrix A like:

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]   11   14   17   20   23   26
[2,]   12   15   18   21   24   27
[3,]   13   16   19   22   25   28

I want to calculate the max and the min difference between two adjacent numbers in all rows. And then filter to limit only rows where adjacent numbers min is less between 4 and 7 and max is between 6 an 12 The output should return no row.

For the following matrix:

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]   11   16   17   28   23   26
[2,]   12   15   18   21   24   27
[3,]   13   16   19   22   25   28

the result should be row 1

Upvotes: 2

Views: 78

Answers (2)

akrun
akrun

Reputation: 887971

Here is a vectorized approach

library(matrixStats)
m1 <- abs(m[,-ncol(m) ] - m[,-1])
m[rowMins(m1) %in% 4:7 & rowMaxs(m1) %in% 6:12,]
#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]   21   15   22   13   23   17
#[2,]   27   18   13   25   16   11

data

set.seed(2)
m <- matrix(sample(11:28, 54, TRUE), nrow = 9)

Upvotes: 1

Jaap
Jaap

Reputation: 83275

You could approach this as follows:

d <- abs(apply(m, 1, diff))

m[apply(d, 2, min) %in% 4:7 & apply(d, 2, max) %in% 6:12,]

which gives:

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]   21   15   22   13   23   17
[2,]   27   18   13   25   16   11

Used data:

set.seed(2)
m <- matrix(sample(11:28, 54, TRUE), nrow = 9)

Upvotes: 3

Related Questions