Help please ! how to break a loop if X=0 and return to the first value

Hello,
I'm looking for a function or method to programm a this loop : if frost_risk = 1 so growth=0 then the growth vector shoud restart from beguinning (it should return the first value of growth vector keeping the main order).

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)

Thank you :slight_smile:

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?

Yes ! thank you so much @jms

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.