0

Is there a way of using cumsum() in R to count the number of zero's instead of 1's? Basically I have a list of only 0's and 1's and every time I encounter a 0 I want to keep count of them and have it not count the 1's.

Cheaumz
  • 33
  • 5
  • 2
    Maybe `cumsum(x==0)`? It would help if you have a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with some sample input data and the desired output for that data. – MrFlick Mar 02 '16 at 06:09
  • Or `cumsum(1-x)` since that will also switch 1's and 0's – thelatemail Mar 02 '16 at 06:23

1 Answers1

2

We create a logical index where the value of the vector ('v1') is 0 ('i1'). Subset the vector with the index, negate it to convert the value 0's to TRUE, do the cumsum and update the original vector by assigning the output back.

i1 <- !v1
v1[i1] <- cumsum(!v1[i1])
v1
#[1] 1 1 1 2 1 3 1 4

If we need to count the adjacent 0's separately i.e.

library(data.table)
ave(v1, rleid(v1), FUN= function(x) if(all(!x)) seq_along(x) else x)
#[1] 1 1 1 2 1 1 1 1

data

v1 <- c(1, 1, 0, 0, 1, 0, 1, 0)
akrun
  • 874,273
  • 37
  • 540
  • 662