Rolling cumulative product

2019-09-16 05:49发布

I have data that looks like this

    A    B    
 1  1    1
 2  3    
 3  5    
 4  7    

where I want to calculate the following rolling cumulative product in column B. In Excel I would have the following formula

B2 = (1 + A2/10)*B1

I so far have tried using a helper column that is the results of 1 + Ax/100 , and one exactly the same just lagged by 1 which then gets multiplied by each other. Which wont work as the rolling product isn't applied. I also tried s.th like

rollapply(columnm,1,FUN = prod, fill = NA, align = 'left')

unfortunately it still doesn't work.

I would expect to get these results for B

    A    B    
 1  1    1
 2  3    1.3
 3  5    1.95
 4  7    3.315

[EDIT]

As an extension to the original question, is there a way of doing the same rolling product in an ifelse statement based on an additional column?

    A    B   C 
 1  1    1   1
 2  3    1   1
 3  5    0
 4  7    0

The excel equivalent would be

C3 = IF(B3=0,(1+A3/10)*C2,1)

I couldn't get the accepted solution working for this case as it is always referring to just the data in column A and I end up with the same results as in the previous solution.

I would expect the following results

    A    B   C 
 1  1    1   1
 2  3    1   1
 3  5    0   1.5
 4  7    0   2.55

thanks in advance

1条回答
聊天终结者
2楼-- · 2019-09-16 06:12

Is this what you want?

A=c(1,3,5,7) 
cumprod(c(1,(A[-1]/10+1)))

> cbind(A,B=cumprod(c(1,(A[-1]/10+1))))
     A     B
[1,] 1 1.000
[2,] 3 1.300
[3,] 5 1.950
[4,] 7 3.315
查看更多
登录 后发表回答