Finding pattern in a matrix in R

前端 未结 7 765
被撕碎了的回忆
被撕碎了的回忆 2020-12-30 04:40

I have a 8 x n matrix, for instance

set.seed(12345)
m <- matrix(sample(1:50, 800, replace=T), ncol=8)
head(m)

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8         


        
7条回答
  •  悲&欢浪女
    2020-12-30 05:27

    Edit: Now, I've added a more generalised function:

    Here's one solution that gives all possible combinations: I obtain all the positions of all four numbers, then use expand.grid to obtain all position combinations and then filter the meaningless ones by checking if each row of the matrix is equal to the corresponding row of the sorted matrix.

    set.seed(12345)
    m <- matrix(sample(1:50, 800, replace=T), ncol=8)
    head(m)
    get_grid <- function(in_mat, vec_num) {
        v.idx <- sapply(vec_num, function(idx) {
            which(apply(in_mat, 1, function(x) any(x == idx)))
        })
        out <- as.matrix(expand.grid(v.idx))
        colnames(out) <- NULL
        out
    }
    
    out <- get_grid(m, c(37, 10, 29, 42))
    out.s <- t(apply(out, 1, sort))
    
    idx <- rowSums(out == out.s)
    out.f <- out[idx==4, ]
    
    > dim(out.f)
    [1] 2946    4
    
    > head(out.f)
         [,1] [,2] [,3] [,4]
    [1,]    1   22   28   36
    [2,]    4   22   28   36
    [3,]    6   22   28   36
    [4,]    9   22   28   36
    [5,]   11   22   28   36
    [6,]   13   22   28   36
    

    These are the row indices of the occurrence of numbers in that order (37, 10, 29, 42).

    From this, you can check any combination you wish. For example, the combination you had asked for can be accomplished by:

    cont.idx <- apply(out.f, 1, function(x) x[1] == x[2]-1 & x[2] == x[4]-1)
    > out.f[cont.idx,]
    [1] 57 58 58 59
    

提交回复
热议问题