1

I have a matrix of 1 and 0. The rules concerning this table is as follows.

I would like to count the number of times a serie of 1,1 appears (where the 1 are not separated by 0!) and make the same thing for a serie of 1,1,1. I have tried colSums but it's seemed not to be very appropriate.

the matrix final is

      t1 t2 t3 t4 t5 t6 t7
 [1,]  0  0  0  0  1  1  0
 [2,]  0  0  1  1  0  0  1
 [3,]  1  1  0  0  0  0  0
 [4,]  0  0  1  1  1  0  0
 [5,]  0  0  1  1  0  0  0
 [6,]  1  1  0  0  0  0  0
 [7,]  0  0  0  0  0  0  1
 [8,]  0  0  0  0  1  1  0
 [9,]  1  1  0  0  1  1  0
[10,]  0  0  0  0  0  1  1
[11,]  1  1  0  0  0  0  0
[12,]  0  0  1  1  0  0  0
[13,]  0  0  0  0  0  0  0
[14,]  0  0  0  0  0  0  1
[15,]  0  0  0  0  0  0  0

Therefore for the first row I would like to have 1 time a serie of 1,1 and 0 time a serie of 1,1,1. For row 4 I would like to have 0 time a serie of 1,1 but 1 time a serie of 1,1,1.

Can anyone tell me whats wrong with the following code for a serie of 1,1?

occ <- matrix()
occ_temp <- matrix
for (j in 1:nrow(final)){
  for (i in 2:7){
    if (sum(final[j,i-1:i])==2){occ_temp[j,i-1]=1}
  }
occ[j] <- sum(occ_temp)
}
richpiana
  • 411
  • 1
  • 7
  • 16

1 Answers1

1

We can loop through the rows with apply, get the run-length-type with rle, extract the lengths where the values are 1, check that are equal to 'n1' and 'n2', and get the sum.

n1 <- 2
n2 <- 3
res <- t(apply(m1, 1, FUN=function(x) {
       x1 <- with(rle(x), lengths[!!values])
       c(sum(x1==n1), sum(x1==n2))
}))
colnames(res) <- paste0("count", c(11, 111))
res
#      count11 count111
# [1,]       1        0
# [2,]       1        0
# [3,]       1        0
# [4,]       0        1
# [5,]       1        0
# [6,]       1        0
# [7,]       0        0
# [8,]       1        0
# [9,]       2        0
#[10,]       1        0
#[11,]       1        0
#[12,]       1        0
#[13,]       0        0
#[14,]       0        0
#[15,]       0        0
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    you are definitivily answering all my question with a remarkable precision. I would like to thank you a lot. I didnt know this function rle, I will have a look – richpiana Feb 22 '16 at 10:17