How to multiply an observation by the previous observation but only if a certain condition is true

Viewed 77

I have data that includes the variables start and weight. I would like to create a new weight that multiples the original weight by the previous weight, and then take this newly created weight and multiply this by the previous weight, so on and so on until the end of the data set. I only would like these new weights to be calculated for all observations where start is greater than 0.

start<-c(0,1,2,3,4,0,1,0,1,0,1,0,0,0,1)
weight<-c(1.427,1.073,1.074,1.074,15.004,1.428,1.073,1.439,1.074,1.416,1.463,1.439,1.074,1.439,1.451)
data<-as.data.frame(cbind(start,weight))

The code I have so far to run the for loop:

for (i in 1:4){
data$new_weight<-ifelse(data$start==i, data$weight * shift(data$weight, 1L, type="lag"), data$weight)
}

Ending up with this dataframe:

new_weight<-c(1.427,1.531,1.645,1.766,26.496,1.428,1.531,1.439,1.546,1.416,1.463,1.439,1.546,1.439,1.451)
data<-cbind(data, new_weight)
data
1 Answers

Perhaps, this helps

library(dplyr)
data %>% 
    group_by(grp = cumsum(start == 0)) %>%
    mutate(weight = cumprod(weight)) %>%
    ungroup %>%
    select(-grp)
Related