Louisa Carter
Louisa Carter

Reputation: 13

Repeating a value when a previous variable value has occured

I have a data set with the following variables: 1. Group 2. Status (Takes on variables 1-7)

I need to create a flag where the following conditions are met: -Flag 1=0 when Status <6, else Flag 1= 1 when Status >=6 -Within each group: If Status has reached 6 or higher and goes back down to below 6, the flag 1 must remain as 1.

The desired table would look as follows:

enter image description here

Upvotes: 0

Views: 74

Answers (3)

Ape
Ape

Reputation: 1169

Using ave to apply a custom function within each group.

df <- data.frame(Group = c(1,2,2,3,3,3,3,4,4), 
                 Status = c(1,2,3,7,6,5,4,5,6))

df$Flag = ave(df$Status, df$Group, FUN = function(x) {cumsum(x >= 6) > 0})

Upvotes: 3

BenoitLondon
BenoitLondon

Reputation: 907

data.table and cummax do the job:

library(data.table)
dt <- data.table(Group = c(1,2,2,3,3,3,3,4,4), 
                 Status = c(1,2,3,7,6,5,4,5,6))
dt[, flag := cummax(Status >= 6), by = Group]
dt

  Group Status flag
1:     1      1    0
2:     2      2    0
3:     2      3    0
4:     3      7    1
5:     3      6    1
6:     3      5    1
7:     3      4    1
8:     4      5    0
9:     4      6    1

Upvotes: 3

Rohit parihar
Rohit parihar

Reputation: 46

df$flag <- ifelse(df$status >6,0,1)

df$status <- ifelse(df$status =>6,5,df$status)

Upvotes: 1

Related Questions