Could someone please help me insert the group_by function (or any function that would do the trick)into this:
df$buy <-ifelse(
(
(df$month %in% c(201909, 201910, 201911, 201912, 202001, 202002)) &
(df$activity== 0)
),
1,
0
)
My data has three columns: ID, Month, and X. Each id has 12-14 observations. I want to group by the id then assign a 1 to all the IDs in a group where month = 201009, 201919, 201911, 201912, 202001, 202002 and X in those rows = 0. For example, buy is the new variable I want to create:
ID MONTH X Buy
1 201901 1 1
1 201002 0 1
1 201903 1 1
1 201904 0 1
1 201905 1 1
1 201906 1 1
1 201907 0 1
1 201908 0 1
1 201909 0 1
1 201910 0 1
1 201911 0 1
1 201912 0 1
1 202001 0 1
1 202002 0 1
2 201901 1 0
2 201902 1 0
2 201903 0 0
2 201904 0 0
2 201905 0 0
2 201906 1 0
2 201907 0 0
2 201908 0 0
2 201909 0 0
2 201910 1 0
2 201911 0 0
2 201912 1 0
2 202001 0 0
2 202002 0 0
I want a 1 for the entire group based on ID only if the months stated above have a zero in the X column, and a zero if it does not meet the requirements. Thank you in advance.