简体   繁体   中英

Cumulative product with r

I want to do something usual in excel but I don't know how to do it with R:

10        * 1.01 = 10.1 
(10+10.1) * 1.02 = 20.502
(10+20.5) * 1.03 = ...

It is like cumprod but * by an external vector.

Edit:

I have two vectors one can be: c(50, 52, 54, 55) and the other one c(1.01, 1.02, 1.03, 1.04) and I want to do:

50 * 1.01 = 50.5
(50.5 + 52) * 1.02 = 104.55
...

I want to get a vector at each step without "for".

Thanks

Try

x <- 1 + 1:100/100 
f <- function(i) 10*sum(cumprod(x[i:1]))
# first 10 elements
sapply(1:10, f)
# [1]  10.10000  20.50200  31.41706  43.07374  55.72743  69.67108  85.24805
# [8] 102.86789 123.02601 146.32861

Answer for edited question: just an adaptation of above.

a <- c(50, 52, 54, 55)
b <- c(1.01, 1.02, 1.03, 1.04)
f1 <- function(i)sum((a[i:1])*cumprod(b[i:1]))
sapply(1:4, f1)
#[1]  50.5000 104.5500 163.3065 227.0388

What about using the following loop?

v <- rep(NA, 3)
for(i in 1:length(v)){
    v[i] <- (max(v[i-1], 0) + 10)*(1 + i/100)
}
v
[1] 10.10000 20.50200 31.41706

If you just want the final product you could create a function:

## Create equal length vectors
x <- rep(10, 10)
y <- seq(1.01, 1.1, .01)

## Create function
accumProd <- function(x, y){
  z = 0
  for (i in 1:length(x)){
    z <- (x[i]+z) * y[i]
  }
  z
}

accumProd(x,y)
[1] 146.3286

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM