Hi Abdel!
I am not entirely sure if I understand what you need. This code loops trough the values of frost_risks
and returns the values of growth
in order. Everytime the loop encounters a 1 in frost_risk
, it starts again with the first value of growth
.
set.seed(4)
growth<-c(0,0,0,0,20,17,21,25,33,35,31,21,12,9,7,5)
frost_risk = rbinom(16, 1, 1/15)
index<-0
growth_new<-vector("numeric",16)
for(i in seq_along(frost_risk)){
if(frost_risk[i]==0) index<-index+1
else index<-1
growth_new[i]<-growth[index]
}
tibble::tibble(growth_new, frost_risk)
#> # A tibble: 16 x 2
#> growth_new frost_risk
#> <dbl> <int>
#> 1 0 0
#> 2 0 0
#> 3 0 0
#> 4 0 0
#> 5 20 0
#> 6 17 0
#> 7 21 0
#> 8 25 0
#> 9 0 1
#> 10 0 0
#> 11 0 0
#> 12 0 0
#> 13 20 0
#> 14 0 1
#> 15 0 0
#> 16 0 0
Created on 2021-02-04 by the reprex package (v1.0.0)
Is that what you were asking for?