Home > Blockchain >  create new var by product of preceding result per goup id in dplyr
create new var by product of preceding result per goup id in dplyr

Time:02-16

I have the follorwing data, and what I need is to create new var new will obtain by product the preceding row values of var Z per group id. eg. the first value of column new is 0.9, 0.90.1, 0.90.1*0.5 for id x=1.

data <- data.frame(x=c(1,1,1,1,2,2,3,3,3,4,4,4,4), 
                   y=c(4,2,2,6,5,6,6,7,8,2,1,6,5),
                   z=c(0.9,0.1,0.5,0.12,0.6,1.2,2.1,0.9,0.4,0.8,0.45,1.3,0.85))

desired outcome

   x y    z    new
1  1 4 0.90 0.9000
2  1 2 0.10 0.0900
3  1 2 0.50 0.0450
4  1 6 0.12 0.0054
5  2 5 0.60 0.6000
6  2 6 1.20 0.7200
7  3 6 2.10 2.1000
8  3 7 0.90 1.8900
9  3 8 0.40 0.7560
10 4 2 0.80 0.8000
11 4 1 0.45 0.3600
12 4 6 1.30 0.4680
13 4 5 0.85 0.3978

CodePudding user response:

We can use the cumprod from base R

library(dplyr)
data %>%
    group_by(x) %>%
    mutate(new = cumprod(z)) %>%
    ungroup

Or with base R

data$new <- with(data, ave(z, x, FUN = cumprod))
  •  Tags:  
  • r
  • Related