Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

writing a loop function in R

say I am working with the below fixed parameters:

#Fixed Parameters
Start<-7200
P1_Input<-10000 #input from current period
P2_Input<-10000 #input from current+1 (next) period
Notional<-3.4*2000
Lot<-round((Start+P1_Input+P2_Input)/Notional,0)
Lot_Unit<-Lot*0.13*2000
Lot_Unit

End_Bal<-Start+Lot_Unit

If I would like to set the value of End_Bal at n=1 to be the next Start value at n=2, keeping all parameters the same and end goal is to find the sum of P1_Input and P2_Input, as well we the End_Bal value at n=20 (or any random number for n, could be 20, 40, 60, etc), am I required to write a loop here? Many thanks for helping.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Because of vectorization, loops are not used as often in R as in other programming languages, but they still have their uses. Feedback loops are a good example of something that isn’t naturally vectorized. A for or while loop is natural in this case:

Start <- 7200
for(i in 1:10){
  P1_Input <- 10000 #input from current period
  P2_Input <- 10000 #input from current+1 (next) period
  Notional <- 3.4 * 2000
  Lot <- round((Start + P1_Input + P2_Input) / Notional, 0)
  Lot_Unit <- Lot * 0.13 * 2000
  Lot_Unit
  End_Bal <- Start + Lot_Unit
  Start <- End_Bal #for next pass through loop
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading