0

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

3 Answers 3

3

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}) 
Sign up to request clarification or add additional context in comments.

Comments

3

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 

Comments

1

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

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

2 Comments

Thanks for this. This solves the first condition but does not address the second condition.
Add another ifelse and give reference of status variable

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.