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?
sum(diff(cmat)==1)
might be a way to do it if there are only binary values.
You could do
sum( cmat[, 1] == 1 & c(NA, head(cmat[, 1], -1)) == 0 , na.rm = TRUE)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With