user3483060
user3483060

Reputation: 407

Count the max number of ones in a vector

I am doing the next task.

Suppose that I have the next vector.

(1,1,0,0,0,1,1,1,1,0,0,1,1,1,0)

I need to extract the next info.

  1. the maximum number of sets of consecutive zeros
  2. the mean number of consecutive zeros.

FOr instance in the previous vector the maximum is: 3, because I have 000 00 0

Then the mean number of zeros is 2.

I am thinking in this idea because I need to do the same but with several observations. I think to implement this inside an apply function.

Upvotes: 1

Views: 129

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101327

You can try another option using regmatches

> v <- c(1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0)

> s <- paste0(v, collapse = "")

> zeros <- unlist(regmatches(s, gregexpr("0+", s)))

> length(zeros)
[1] 3

> mean(nchar(zeros))
[1] 2

Upvotes: 1

akrun
akrun

Reputation: 887088

We could use rle for this. As there are only binary values, we could just apply the rle on the entire vector, then extract the lengths that correspond to 0 (!values - returns TRUE for 0 and FALSE others)

out <-  with(rle(v1), lengths[!values])

And get the length and the mean from the output

> length(out)
[1] 3
> mean(out)
[1] 2

data

v1 <- c(1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0)

Upvotes: 3

Related Questions