[Solved] Detect the position of a pattern of numbers in a matrix in R [closed]


According to your new rules, may be this helps:

data1 <- data
#changing some elements to test the code
data1[2,8] <-2 
data1[4,1] <- 1

##The code is for the row

indx <- which(t(sapply(split(data1 == pattern, row(data1)), {
function(x) colSums(sapply(1:(length(x) - 3), function(i) x[seq(i, i + 3)]), 
    na.rm = TRUE) == 4
})), arr.ind = TRUE)
indx
# row col
# 3   3   1
#3   3   2
#4   4   2
#3   3   3
#4   4   3
#3   3   4
#3   3   5
#3   3   6
#3   3   7
#3   3   8
#3   3   9
#3   3  10
#3   3  11

A correction in previous code for colwise operation

 which(apply(pattern==data, 2, function(x){if(all(!is.na(x) & x)) x else rep(FALSE, 4)}),arr.ind=TRUE)

Changing the pattern to 1

 pattern <- rep(1,4)
  which(apply(pattern==data, 2, function(x){if(all(!is.na(x) & x)) x else rep(FALSE, 4)}),arr.ind=TRUE)
 #row col

0

solved Detect the position of a pattern of numbers in a matrix in R [closed]