Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flag the first occurrence of a number and all rows after

Tags:

r

I have a df in R that tracks the status whether an individual is single (0), married (1), or divorced (99) overtime.

ID <- c(1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5)
STATUS <- c("0", "0", "0", "1", "1", "1", "99", "99", "1", "0", "1")
df <- data.frame(ID, STATUS)
df

I would like to create a new variable which flags the first time the individual is divorced (STATUS = 99) and any rows after that point. For example under the STATUS column, ID 1 was single for three periods, then was divorced for three periods column, and later got married again. The "flag" column flags the first 99 that appears and all events after that row for each ID.

The final product should look like:

  ID STATUS    FLAG
   1      0      0
   1      0      0
   1      0      0
   1      1      0
   1      1      0
   1      1      0
   1     99      1
   1     99      1
   1      1      1
   5      0      0
   5      1      0
like image 216
Kristine Avatar asked Oct 28 '25 21:10

Kristine


2 Answers

One possibility using dplyr:

df %>%
 group_by(ID) %>%
 mutate(flag = +(row_number() >= min(which(STATUS == 99))))

      ID STATUS  flag
   <dbl> <fct>  <dbl>
 1    1. 0         0.
 2    1. 0         0.
 3    1. 0         0.
 4    1. 1         0.
 5    1. 1         0.
 6    1. 1         0.
 7    1. 99        1.
 8    1. 99        1.
 9    1. 1         1.
10    5. 0         0.
11    5. 1         0.

Or a possibility based on the solution from @markus:

df %>%
 group_by(ID) %>%
 mutate(flag = cummax(STATUS == 99))

Or with base R:

df$flag <- ave(df$STATUS, df$ID, FUN = function(x) +(1:nrow(df) >= min(which(x == 99))))
like image 119
tmfmnk Avatar answered Oct 30 '25 11:10

tmfmnk


We can use cummax by group

df$FLAG <- with(df, ave(STATUS, ID, FUN = function(x) cummax(x == 99)))
df
#   ID STATUS FLAG
#1   1      0    0
#2   1      0    0
#3   1      0    0
#4   1      1    0
#5   1      1    0
#6   1      1    0
#7   1     99    1
#8   1     99    1
#9   1      1    1
#10  5      0    0
#11  5      1    0
like image 37
markus Avatar answered Oct 30 '25 13:10

markus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!