Calculate a rolling sum of consecutive TRUE values for a logical vector or "1" values for a binary vector. The total will continue increasing as it moves along the vector and encounters only 1/TRUE, then will reset after encountering a 0/FALSE value. When working with monthly service utilization data with rows organized by ID and month, this is useful for estimating things like how many consecutive months someone used a service.

consum(x, skip_na = FALSE)

Arguments

x

the logical or binary vector to summed.

skip_na

Should consecutive counting resume or reset after encountering a missing value (NA)? Default is FALSE.

Value

A numeric vector of the same length as x with the consecutive total.

See also

Author

Craig P. Hutton, Craig.Hutton@gov.bc.ca

Examples


x <- c(rep(1, 8), rep(0, 5), rep(1, 4), rep(NA_real_, 2), rep(1, 6))

consum(x)
#>  [1]  1  2  3  4  5  6  7  8  0  0  0  0  0  1  2  3  4 NA NA  1  2  3  4  5  6

consum(x, skip_na = TRUE)
#>  [1]  1  2  3  4  5  6  7  8  0  0  0  0  0  1  2  3  4 NA NA  5  6  7  8  9 10