rdataframewhile-loopsequencing

Sequentially reduce values in a column in R


I am currently trying to reduce the values in a column by a certain total amount, until that amount reaches zero. For example, in the data frame created by this code:

df = data.frame(matrix(0,nrow=10,ncol=2))
colnames(df) <- c("AccountNumber", "BuyAmount")
overbuy <- 500000
df$AccountNumber <- seq(1:10)
df$BuyAmount <- c(35000, 220000, 240000, 0, 195000, 55000, 0, 280000, 65000, 105000)

>df
   AccountNumber BuyAmount
1              1     35000
2              2    220000
3              3    240000
4              4         0
5              5    195000
6              6     50000
7              7         0
8              8    280000
9              9     65000
10            10    105000

I am trying to reduce the nonzero values in the BuyAmount column by 5000 at a time, running along the column and reducing the value of overbuy by 5000 each time. After the first run through the loop, df should look like so:

>df
   AccountNumber BuyAmount
1              1     30000
2              2    215000
3              3    235000
4              4         0
5              5    190000
6              6     45000
7              7         0
8              8    275000
9              9     60000
10            10    100000

And the value of overbuy should be reduced by 40000 to 460000. I would like this loop to continue to run over these values until overbuy reaches 0. In theory, df would end as

>df
   AccountNumber BuyAmount
1              1         0
2              2    150000
3              3    170000
4              4         0
5              5    130000
6              6         0
7              7         0
8              8    210000
9              9         0
10            10     35000

once overbuy reaches 0. My current attempt is:

while(overbuy > 0){
  for(1 in 1:10){
    ifelse(df$BuyAmount[i] != 0, df$BuyAmount[i] <- df$BuyAmount[i] - 5000, "")
    overbuy <- overbuy - 5000
  }
}

Any help would be appreciated!


Solution

  • I think this works, but it's not elegant and I might not have fully understood your goal. If not, let me know and I'll fix this.

    EDITED:

    while(overbuy > 0){
        for(i in 1:10){
    
            if(df$BuyAmount[i]!=0){
                overbuy <- overbuy - 5000
            }
            df$BuyAmount[i] <- pmax(0, df$BuyAmount[i] - 5000)
    
            print(overbuy)
            print(df)
            if(overbuy == 0) break
        }
    }