Search code examples
rpattern-matchingdetection

Detect the position of a pattern of numbers in a matrix in R


I am looking for a R function which detect the position of a pattern (vector of numbers) in a matrix or a data frame of numbers.

Thanks

Stéphane

example :

pattern <- c(2,2,2,2)
data<-t(data.frame(
    v1 = c(2,2,2,1,0,0,0,0,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA),
    v2 = c(2,2,2,9,9,0,0,0,0,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA),
    v3 = c(2,2,2,2,2,2,2,2,2,2,2,2,2,2,9,1,1,0,0,0),
    v4 = c(2,2,2,2,2,2,0,1,1,1,0,0,0,0,NA,NA,NA,NA,NA,NA)))

Solution

  • 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