I'm trying to build a more custom version of cumsum
to use on a data.table, but I'm failing at the first step:
numbers <- data.table(num=1:10)
sum <- 0
cumFunct <- function(n) {
sum <<- sum+n
return(sum)
}
numbers[, cum:=sapply(num, cumFunct)]
While this works, it is very unclean. It also requires sum to be set to 0 before I run the function.
Now, how do I write this in a cleaner way? Essentially, how can I pass the intermediate result to the next iteration of cumFunct
without using global variables?
Thanks very much!