匹配矩阵中的模式

hei*_*heo -2 r matrix pattern-matching

我的数据如下:

                         S  
0101001010000000000000000100111100000000000011101100010101010
1001010000000001100000000100000000000100000010101110101010010
1101010101010010000000000100000000100101010010110101010101011
0000000000000000001000000111000110000000000000000000000000000
Run Code Online (Sandbox Code Playgroud)

S表示我正在谈论的列.它是col 26.所有四行在该位置共享1.

我需要能够计算从2到4的每一行:

  • 左侧和右侧的列数与第1行相同?

对于第2行,它将是右边的3(当它达到1/0时)和左边的8(当它达到0/1时).

应该将每行的结果输入到这样的矩阵中:

row2 8 3
row3 11 9
Run Code Online (Sandbox Code Playgroud)

是否有快速有效的方法来做到这一点?我正在处理的矩阵非常大.

Rol*_*and 5

如果你需要快速的东西,你可以使用Rcpp:

mat <- as.matrix(read.fwf(textConnection("0101001010000000000000000100111100000000000011101100010101010
1001010000000001100000000100000000000100000010101110101010010
1101010101010010000000000100000000100101010010110101010101011
0000000000000000001000000111000110000000000000000000000000000"), widths = rep(1, 61)))


library(Rcpp)

cppFunction('
    IntegerMatrix countLR(const LogicalMatrix& mat, const int S) {
       const int nr(mat.nrow()), nc(mat.ncol());
       IntegerMatrix res(nr - 1, 2);
       for(int i=1; i<nr;i++){
         for(int j=S-2; j>=0;j--) {
           if (mat(0,j) != mat(i,j)) break;
           else res(i-1,0)++;
         }
         for(int j=S; j<nc;j++) {
           if (mat(0,j) != mat(i,j)) break;
           else res(i-1,1)++;
         }
       }
       return(res);
    }' ) 


countLR(mat, 26)
#     [,1] [,2]
#[1,]    8    2
#[2,]   10    2
#[3,]    6    0
Run Code Online (Sandbox Code Playgroud)

我认为第26列本身不计算结果.我还假设矩阵只能包含0/1(即布尔值).根据需要调整.