Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find consecutive TRUE values in a vector and replace them with the amount of consecutive TRUE values in R?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading