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:
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!
CodePudding user response:
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