Home > Software engineering >  How to find consecutive TRUE values in a vector and replace them with the amount of consecutive TRUE
How to find consecutive TRUE values in a vector and replace them with the amount of consecutive TRUE

Time:10-13

Good morning,

I am sure there is an easy way to do this (in fact, I remember having done it in the past, but I do not remember how).

I have a logical variable in a dataframe which is compounded by consecutive TRUE and FALSE values:

dput(vel)
c(FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, 
TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, 
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 
TRUE, TRUE, TRUE, TRUE)

What I would like to obtain is a new vector, of the same length, that every time there is a FALSE value, replace it by 0, and every time there is one or more consecutive TRUE values, replace them with the number of consecutive TRUE values, repeatedly.

From the example above, this is what I would like to obtain:

> vel.con
 [1]  0  0  0  2  2  0  5  5  5  5  5  0  0  0  0  0  0  0  0 15 15 15 15 15
[25] 15 15 15 15 15 15 15 15 15 15

I have found other ways to solve the problem, but none repeating the value (e.g. 5,5,5,5,5) instead of creating a counting (e.g. 1,2,3,4,5). What I want to obtain is the former.

Thank you very much in advance for the help!

CodePudding user response:

You can use rle here and rep

tmp <- rle(x)
with(tmp, rep(lengths * values, lengths))
#  [1]  0  0  0  2  2  0  5  5  5  5  5  0  0  0  0  0  0  0  0 15
# [21] 15 15 15 15 15 15 15 15 15 15 15 15 15 15

Where

x <- c(FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, 
       TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, 
       TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 
       TRUE, TRUE, TRUE, TRUE)

CodePudding user response:

Just an alternative to @markus answer, using data.table

data.table(x)[,v:=.N, rleid(x)][!x,v:=0][,v]

Output:

[1]  0  0  0  2  2  0  5  5  5  5  5  0  0  0  0  0  0  0  0 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15
  • Related