LearneR
LearneR

Reputation: 2531

How to count a change of number in a matrix in R?

I've a matrix called 'cmat':

> cmat
      [,1]
 [1,]    0
 [2,]    0
 [3,]    0
 [4,]    1
 [5,]    0
 [6,]    1
 [7,]    0
 [8,]    1
 [9,]    0
[10,]    1
[11,]    1
[12,]    1
[13,]    0
[14,]    0
[15,]    1
[16,]    0
[17,]    1
[18,]    0
[19,]    0
[20,]    1
[21,]    0
[22,]    1
[23,]    0

Now, what I'm trying to achieve is I want to count the number of times the value has become 1 from a previous value of 0. How to do this in R?

Upvotes: 5

Views: 184

Answers (3)

Carl Witthoft
Carl Witthoft

Reputation: 21502

Just adding an alternative here. rle(cmat) will let you identify every location at which the value changes as well as the new value.

Upvotes: 1

lukeA
lukeA

Reputation: 54237

You could do

sum( cmat[, 1] == 1 & c(NA, head(cmat[, 1], -1)) == 0 , na.rm = TRUE)

Upvotes: 3

Francis
Francis

Reputation: 6726

sum(diff(cmat)==1) might be a way to do it if there are only binary values.

Upvotes: 7

Related Questions