'Reiterative calculate

I have to make a reiterative table that each calculation has to take the previous one. Let me explain, my initial data are:

maximum <- 10
minimum <- 2
orderp <-0
Qst <- 6
sell <- c(0, 2 , 2 , 10)

Calculated:

Qst <- c(6, 4, 2, 0)
Qfin <- c(6,4, 10, 10)
orderp <- c(0,0,8,10)
output<-data.frame(Qst,Qfin,sell)
Name 1 2 3 4
Qst 6 6-2=4 (Qfin(1)-sell(2) 4-2=2 (Qfin(2)-sell(3) 10-10=0 (Qfin(3)-sell(4)
orderp 0 0 if(Qst(2) <=min) MAX-Qst(2) 8 if(Qst(3) <=min) MAX-Qst 10 if(Qst(4) <=min) MAX-Qst
Qfin 6 4 (Qst(2)+orderp(2) 10 (Qst(3)+orderp(3) 10 (Qst(4)+orderp(4)
sell 0 2 2 10

How can I do something like this? Excel is easy but R is not my field.

r


Solution 1:[1]

I think this requires a small loop to solve, as it is an iterative calculation:

for(i in 2:length(sell)) {
  Qst[i] <- Qfin[i - 1] - sell[i]
  orderp[i] <- ifelse(Qst[i] <= minimum, maximum - Qst[i], 0)
  Qfin[i] <- Qst[i] + orderp[i]
}

This results in:

rbind(Qst, orderp, Qfin, sell)
#>        [,1] [,2] [,3] [,4]
#> Qst       6    4    2    0
#> orderp    0    0    8   10
#> Qfin      6    4   10   10
#> sell      0    2    2   10

Created on 2022-05-13 by the reprex package (v2.0.1)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Allan Cameron