I need create a id sequence for a specific condition: flag==1, an example of my problem is:
library(dplyr)
set.seed(123)
a <- data.frame(id = 1:10,
flag = rbinom(10,1,0.2))
print(a)
id flag
1 1 0
2 2 0
3 3 0
4 4 1
5 5 1
6 6 0
7 7 0
8 8 1
9 9 0
10 10 0
I tried to create a id variable only for flag==1 but lamentably also identify flag==0, an example of my command result and desire result is :
a %>%
mutate(try_seq = cumsum(c(TRUE, diff(flag) != 0)))
> id flag try_seq desire_seq
1 1 0 1 NA
2 2 0 1 NA
3 3 0 1 NA
4 4 1 2 1
5 5 1 2 1
6 6 0 3 NA
7 7 0 3 NA
8 8 1 4 2
9 9 0 5 NA
10 10 0 5 NA
10 10 0 5 NA
This will return the result you are looking for:
cumsum(c(a$flag[1], diff(a$flag)) > 0) * NA^!a$flag
[1] NA NA NA 1 1 NA NA 2 NA NA
The NA^a$flag trick uses the idea that any value raised to the 0th power is 1. Otherwise, we use diff to check for a positive change in variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With