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

Is there a good way to make the rest of value 1 within a id if the previous value is 1 in r

I am trying to make the rest of visit value to 1 if the previous value is 1 within the same id, but just can’t find a good way without a bunch of slow for loops.

Here is the example:

data.frame(ID = c(1,1,1,1,1,2,2,2,2,2,2,3,3,3), 
           Visit = c(1,2,3,4,5,1,2,3,4,5,6,1,2,3), 
           Value = c(0,0,1,0,0,0,0,0,0,1,0,0,1,0))

And here is what I want to get:

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

data.frame(ID = c(1,1,1,1,1,2,2,2,2,2,2,3,3,3), 
           Visit = c(1,2,3,4,5,1,2,3,4,5,6,1,2,3), 
           Value = c(0,0,1,1,1,0,0,0,0,1,1,0,1,1))

Thanks in advance!

>Solution :

We could use cummax to return 1 for rest of the values after grouping by ‘ID’

library(dplyr)
df1 %>% 
   group_by(ID) %>%
   mutate(Value = cummax(Value))%>%
   ungroup

-output

# A tibble: 13 × 3
      ID Visit Value
   <dbl> <dbl> <int>
 1     1     1     0
 2     1     2     0
 3     1     3     1
 4     1     4     1
 5     2     1     0
 6     2     2     0
 7     2     3     0
 8     2     4     0
 9     2     5     1
10     2     6     1
11     3     1     0
12     3     2     1
13     3     3     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