test <- structure(list(i = c(0, 1, 2, 3, 4, 0, 1, 2, 3, 4), chng = c(0,
0.031, 0.005, -0.005, 0.017, 0, 0.012, 0.003, -0.013, -0.005),
indx = c(1, 1.031, 1.037, 1.031, 1.048, 1, 1.012, 1.015,
1.002, 0.997)), class = "data.frame", row.names = c(NA, -10L
))
test %>%
group_by(g = cumsum(i == 0)) %>%
mutate(indx = cumprod(chng + 1)) %>%
ungroup %>%
select(-g)
we could write using one fewer statement, i.e. the last two lines of code above are combined into the last line below.
test %>%
group_by(g = cumsum(i == 0)) %>%
mutate(indx = cumprod(chng + 1)) %>%
ungroup(-g)
Note the reduced line count and improved symmetry.
A common case is that one constructs a grouping variable in
group_bybut only needs it for the duration of thegroup_byso afterwards one must useselectto get rid of it as in the example below. It would be pleasingly symmetric ifungroupcould remove the added column just asgroup_byadds it sowould be the same as
Thus in this example taken from https://stackoverflow.com/questions/51939874/referencing-previous-column-value-as-column-is-created/51940343#51940343
we could write using one fewer statement, i.e. the last two lines of code above are combined into the last line below.
Note the reduced line count and improved symmetry.