Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 650
LearneR Avatar asked Apr 15 '15 09:04

LearneR


2 Answers

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

like image 160
Francis Avatar answered Oct 15 '22 23:10

Francis


You could do

sum( cmat[, 1] == 1 & c(NA, head(cmat[, 1], -1)) == 0 , na.rm = TRUE)
like image 35
lukeA Avatar answered Oct 16 '22 00:10

lukeA