I have a data.table as follows
set.seed(5) x <- data.table(x=sample(1:20,15)) > x x 1: 5 2: 14 3: 17 4: 20 5: 2 6: 11 7: 8 8: 15 9: 12 10
We can use Reduce with accumulate = TRUE
Reduce
accumulate = TRUE
accum <- Reduce(function(i, j) i + x$x[i], x$x, accumulate = TRUE) c(1, accum[!is.na(accum)]) # [1] 1 5 7 15 28
or purrr::accumulate
purrr::accumulate
library(purrr) accum <- accumulate(x$x, ~ .x + x$x[.x]) c(1, accum[!is.na(accum)]) # [1] 1 5 7 15 28