I'm trying to create a new variable `Rd` that will take the value `lag(Rd)`if the variable `Vol` is equal to 0. Else it will take the value `OI/CumVol`. This computation is done by `Group`, so in case for the first observation, the variable `Vol` is equal to 0, I set `Rd=0`.
Here is an example of what I want :

```
  Group   Vol      OI   CumVol   Rd   
  <date>   <dbl> <dbl> <dbl>    <dbl>
  2008-08-10  0     0      0       0      
  2008-08-10  100   100    100     1
  2008-08-10  0     100    300     1
  2008-08-10  0     100    400     1     
  2008-08-10  50    150    550    0.27
  2009-12-10  0     150     0      0 
  2009-12-10  50    30    50      0.6
  2009-12-10  0     20     50     0.6

```

I have tried to mutate twice with the lag, but the problem is in case the `Vol` = 0 for repeated rows, it always takes the lag for the first row, and continues with 0 for the others.

```
Data1<-Data1 %>%
group_by(Group) %>%
mutate(Rd1 = ifelse(Vol==0, 0, (Data1$OI/Data1$CumVol)))

Data1<-Data1 %>%
group_by(Group) %>%
mutate(Rd = ifelse(Vol==0, lag(Rd1), 
(Data1$OI/Data1$CumVol)))

```

Thanks for everyone that will take the time to answer.