As Paul points out, iteration is needed. You have a dependency between one instance and the previous point.
However, a dependency only occurs whenever a purchase is made (read: you only need to recalculate the balance when ...). This way you can iterate in batches
Try the following to determine which next line contains enough balance to make a purchase. Then it processes all the previous lines in one call and then goes to that point.
library(data.table) DT <- as.data.table(df) ## Initial Balance b.init <- 2 setattr(DT, "Starting Balance", b.init) ## Raw balance for the day, regardless of purchase DT[, balance := b.init + cumsum(income)] DT[, buying := FALSE] ## Set N, to not have to call nrow(DT) several times N <- nrow(DT) ## Initialize ind <- seq(1:N) # Identify where the next purchase is while(length(buys <- DT[ind, ind[which(price <= balance)]]) && min(ind) < N) { next.buy <- buys[[1L]] # only grab the first one if (next.buy > ind[[1L]]) { not.buys <- ind[1L]:(next.buy-1L) DT[not.buys, buying := FALSE] } DT[next.buy, `:=`(buying = TRUE , balance = (balance - price) ) ] # If there are still subsequent rows after 'next.buy', recalculate the balance ind <- (next.buy+1) : N # if (N > ind[[1]]) { ## So that DT[ind, balance := cumsum(income) + DT[["balance"]][[ ind[[1]]-1L]] ] # } } # Final row needs to be outside of while-loop, or else will buy that same item multiple times if (DT[N, !buying && (balance > price)]) DT[N, `:=`(buying = TRUE, balance = (balance - price)) ]
Results:
## Show output { print(DT) cat("Starting Balance was", attr(DT, "Starting Balance"), "\n") } ## Starting with 3: dates price income balance buying 1: 1 5 2 0 TRUE 2: 2 2 2 0 TRUE 3: 3 3 2 2 FALSE 4: 4 5 2 4 FALSE 5: 5 2 2 4 TRUE 6: 6 1 2 5 TRUE Starting Balance was 3 ## Starting with 2: dates price income balance buying 1: 1 5 2 4 FALSE 2: 2 2 2 4 TRUE 3: 3 3 2 3 TRUE 4: 4 5 2 0 TRUE 5: 5 2 2 0 TRUE 6: 6 1 2 1 TRUE Starting Balance was 2 # I modified your original data slightly, for testing df <- rbind(df, df) df$dates <- seq_along(df$dates) df[["price"]][[3]] <- 3
source share