Home > Back-end >  writing a loop function in R
writing a loop function in R

Time:10-25

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.

CodePudding user response:

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
}
  • Related