I have a data frame as follows:
df_ex <- tibble(
id = c(1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2),
flag = c(1,0,0,1,1,0,0,0,1,1,0,0,1,0,0,0,0,0),
flag_new = c(1,1,1,1,1,0,0,0,1,1,1,1,1,0,0,0,0,0)
)
let's assume I have a variable called flag, so for each id, I want to check the number of zeros between ones in that variable. If I have one and there are up to 4 zeros and then there is another one, I would like to replace the zeroes with ones (between the ones). I have made a variable called flag_new that is the real flag that I am trying to generate.
Thanks for your help in advance.