Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cumulative sum equation using for loop

I don't have a lot of experience with R, but I want to put an equation that uses a cumulative sum into R-studio. The equation is part of a set of discrete time equations, that are all modeled via for loops. Basically, I want to model this, but in a more simple way:

Zsec1 = g*(1+c/r+c)*Zprim1

Zsec2 = g*(1+c/r+c)*Zprim1 + g*(1+c/r+c)*Zprim2

Zsec3 = g*(1+c/r+c)*Zprim1 + g*(1+c/r+c)*Zprim2 + g*(1+c/r+c)*Zprim3 
..etc

Based on what I could find online, I tried using a for loop like this:

for (t in Time) print(cumsum({gamma*((1+c4)/(r+c4))*Zprm[t]})) 

however the cumsum code does not do anything, as i get the same result when I take it out.

and like this:

total=0

for (t in Time) print({total <- total + (gamma*((1+c4)/(r+c4))*Zprm[t])})    

Is there anyone that could please help me with this? Thank you very much!

like image 378
J. Bl Avatar asked Mar 10 '26 11:03

J. Bl


1 Answers

This is basically the answer of the first comment. I just find it more intuitive to isolate the factor before taking the cumsum.

g*(1+c/r+c)*cumsum(Zprm[1:Time])[Time]
like image 110
otwtm Avatar answered Mar 13 '26 16:03

otwtm