cmdublin
cmdublin

Reputation: 21

How to count group of consecutive values by observation in R

I simply want to count the number of groups of consecutive zeros in R. The 'TotalObsCount' is the desired output. I know I'm on the right track with the below code but I can't seem to tweak it correctly. Example Dataframe:

df <- data.frame(col1 = c(0, 0, 1, 1, 1, 0, 0, 0, 0),
                 col2 = c(0, 0, 0, 0, 0, 1, 0, 0, 0),
                 col3 = c(0, 1, 0, 0, 0, 1, 0, 0, 0),
                 col4 = c(1, 0, 0, 1, 0, 0, 1, 0, 0),
                 col5 = c(0, 0, 1, 0, 1, 0, 0, 1, 1))

TotalObsCount <- c(1, 2, 1, 1, 1, 1, 1, 1, 1)

Example of code

    most_consecutive_val = function(x, val = 0) {with(rle(x), if(all(values != val)) 0 else max(lengths[values == val]))}
    apply(df[-1], MARGIN = 1, most_consecutive_val)

Upvotes: 0

Views: 58

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 174476

I think you're looking for

apply(df, 1, function(x) length(which(rle(x)$values == "0" & rle(x)$lengths > 1)))
#> [1] 1 2 1 1 1 1 1 1 1

Upvotes: 3

Related Questions