data <- data.frame(ID = c(13579,13579,13579,13579,13579,13579,13579,13579,13579,13579,13579,13579,13579,
13579,13579,13579,13579,13579,13579,13579,13579,13579,13579,13579,13579,13579,
13579, 13579, 13579, 13579, 13579, 13579, 13579),
days_from_next_visit = c(20,25,28,29,10,32,27,18,15,18,29,27,22,24,20,25,24,35,2,50,35,50,60,
20,17,5,14,29,40,50,31,21,0),
flg_30day = c(0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,0,0,0,0,0,1,1,1,0))
desired output - cumulative should be reset on one of the 2 conditions either when the cumulative hits 180 or when the days_from_next_visit is greater than 30 .
cumsum - 20 45 73 102 112 144 27 45 60 78 107 134 156 180 20 45 69 104 2 52 35 50 60 20 37 42 56 85 125 50 31 21 21
cum_count - 1 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 1 0 1 1 1 1 0 0 0 0 0 1 1 1 0