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

R find at least 10 consecutive 1s in a row

I have a column DuchenneMarker with the values 0 and 1.
I want to find at least 10 consecutive 1s and mark them in a new column DuchenneSmiles like this:

DuchenneMarker DuchenneSmiles
0              0
0              0            
0              0
1              0
1              0
0              0
1              1 
1              1 
1              1 
1              1 
1              1 
1              1 
1              1 
1              1 
1              1 
1              1 
1              1 

I’ve already tried it with stats:filter() and dplyr::filter() but it didn’t worked.
Is there a function that I should use or a brute-force method?

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

>Solution :

With the tidyverse you could do something like this. It creates a dummy grouping variable run for each run of 0s or 1s and removes it at the end.

df %>% 
  group_by(run = cumsum(DuchenneMarker != lag(DuchenneMarker, default = 0))) %>% 
  mutate(DuchenneSmiles = 0L + (n() > 9 & DuchenneMarker == 1)) %>% 
  ungroup() %>% 
  select(-run)

# A tibble: 17 × 2
   DuchenneMarker DuchenneSmiles
            <int>          <int>
 1              0              0
 2              0              0
 3              0              0
 4              1              0
 5              1              0
 6              0              0
 7              1              1
 8              1              1
 9              1              1
10              1              1
11              1              1
12              1              1
13              1              1
14              1              1
15              1              1
16              1              1
17              1              1
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