1

I have a matrix which encompasses values equal either to "J" or "N". These values appear in a block of 3, 2 or 1 and are separated by no values. I would like to count of many times a block of 3,2 and 1 appear. I could manage to do it when I replace J and N by 1 and then count it according to the next function. However, how can you do it to separate between J and N. Thanks

The matrix:

      t1 t2 t3 t4 t5 t6 t7
 [1,]  0  0  0  0  J  J  0
 [2,]  0  0  N  N  0  0  N
 [3,]  J  J  J  0  0  0  0
 [4,]  0  0  N  N  N  0  0

The code (from someone in the chat)for J

n1 <- 2
n2 <- 3
res <- t(apply(Calendar, "J", FUN=function(x) {
       x1 <- with(rle(x), lengths[!!values])
       c(sum(x1==n1), sum(x1==n2))
}))
colnames(res) <- paste0("count", c(11, 111))
res

Well it does not work.At the end I would like to have a matrix (according to the initial matrix)

J3 J2 J1 N3 N2 N1
1  2  0  1  1  1

Edit and request for clarification: Under the assumption that this is a calendar and 1-7 are days of the week, what would be the desired answer to this potential matrix:

The matrix:

      t1 t2 t3 t4 t5 t6 t7
 [1,]  0  0  0  0  0  J  J
 [2,]  J  0  N  N  0  0  N
 [3,]  J  J  J  0  0  0  N
 [4,]  N  0  N  N  N  0  0
IRTFM
  • 258,963
  • 21
  • 364
  • 487
richpiana
  • 411
  • 1
  • 7
  • 16

1 Answers1

1

We can use rle

lst1 <- lapply(c("J", "N"), function(nm) t(apply(Calendar == nm, 1,
          FUN = function(x) {
             x1 <- with(rle(x), lengths[values])
             table(factor(x1, levels=1:3))})))
`row.names<-`(t(sapply(lst1, colSums)), c("J", "N"))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • thanks a lot youre also the one who helped me last time. I have another question. I want to run a fonction but column by column but its very important that the function is apply first to the first column and then to the second. Is apply the best solution or a loop is better (since i dont want to apply my function to every column at ounce). Thanks for your help and have a nice day – richpiana Jul 09 '16 at 12:30
  • @branchwarren If the first columns output affect the second column in each run, it may be better to use a `for` loop. – akrun Jul 09 '16 at 12:32