A sample of data I have.
hour <- c(rep(0,5), rep(1,5),rep(0,5), rep(1,5))
rain <- c(rep(0.1,10),rep(0.0,10))
df1<-data.frame(rain,hour)
df1$csum <- with(df1, ave(df1$hour, cumsum(df1$hour == 0), FUN = cumsum))
Steps:
1. Find values of 1 in 'csum' (6th/16th).
2. Look at values 3 rows up and 5 down in 'rain' (1:9/11:19 in this case), around position determined by 1st step in var 'csum',
3. if their sum is >= 0.1; than first three values of 1 in var 'hour' (6:8) are converted to 0, in second case they are staying the same because sum is 0.
Expected output: First three values of 1 in df1$hour are switched to 0
hour = c(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1)
there could be much improvements to this sol: