Cheaumz
Cheaumz

Reputation: 33

Using cumsum() in R to count number of zeros instead of 1's

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.

Upvotes: 0

Views: 147

Answers (1)

akrun
akrun

Reputation: 887911

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)

Upvotes: 2

Related Questions