dataframe - Sequentially reduce values in a column in R -


i trying reduce values in column total amount, until amount reaches zero. example, in data frame created 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 trying reduce nonzero values in buyamount column 5000 @ time, running along column , reducing value of overbuy 5000 each time. after first run through loop, df should 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 value of overbuy should reduced 40000 460000. loop continue run on these values until overbuy reaches 0. in theory, df 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. 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 appreciated!

i think works, it's not elegant , might not have understood goal. if not, let me know , 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     } } 

Comments