Here are a few alternatives using only the R base:
1) Reduce
sumprod <- function(x, y) if (y < 1) x * y else x + y
Reduce(sumprod, x, acc = TRUE)
2) Recursion
cumsumprod_ <- function(x, init) {
if (length(x)) c(init, Recall(x[-1], sumprod(tail(init, 1), x[1])))
else init
}
cumsumprod <- function(x) {
if (length(x) < 2) x
else cumsumprod_(x[-1], x[1])
}
cumsumprod(x)
Update: Fixed edge in (2).
source
share