r - Matching patterns in a matrix -
my data looks this:
s 0101001010000000000000000100111100000000000011101100010101010 1001010000000001100000000100000000000100000010101110101010010 1101010101010010000000000100000000100101010010110101010101011 0000000000000000001000000111000110000000000000000000000000000
the s indicates column talking. col 26. 4 rows share 1 @ position.
i need able count each row 2 4:
- how many columns left , right same row 1?
for row 2 3 right (as reaches 1/0) , 8 left (as reaches 0/1).
the result every row should entered matrix this:
row2 8 3 row3 11 9
is there fast , efficient way that? matrix dealing large.
if need fast, use 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
i assumed column 26 doesn't count result. assumed matrix can contain 0/1 (i.e., boolean) values. adjust needed.
Comments
Post a Comment