GabrielMontenegro
GabrielMontenegro

Reputation: 762

Estimate how many consecutives true elements there is in a vector in R

I have a really large boolean vector (i.e. T or F) and I want to simply be able to estimate how many "blocks" of consecutive T there are in my vector contained between the F elements.

A simple example of a vector with 3 of these consecutive "blocks" of T elements:

x <- c(T,T,T,T,F,F,F,F,T,T,T,T,F,T,T)

Output:

1,1,1,1,0,0,0,0,2,2,2,2,0,3,3

Upvotes: 2

Views: 64

Answers (2)

tmfmnk
tmfmnk

Reputation: 39858

You can do:

rle <- rle(x)
rle$values <- with(rle, cumsum(values) * values)
inverse.rle(rle)

[1] 1 1 1 1 0 0 0 0 2 2 2 2 0 3 3

And a simplified and more elegant version of the basic idea (proposed by @Lyngbakr):

with(rle(x), rep(cumsum(values) * values, lengths))

Upvotes: 5

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84529

Another solution with rle/inverse.rle:

x <- c(T,T,T,T,F,F,F,F,T,T,T,T,F,T,T)
rle_x <- rle(x)
rle_x$values[rle_x$values] <- 1:length(which(rle_x$values))
inverse.rle(rle_x)
# [1] 1 1 1 1 0 0 0 0 2 2 2 2 0 3 3

Upvotes: 1

Related Questions