正如保罗所指出的,一些迭代是必要的。您在一个实例和前一个点之间存在依赖关系。
但是,依赖关系仅在购买时发生(阅读:您只需要重新计算余额时......)。因此,您可以“批量”迭代
通过确定下一行有足够的余额进行购买,请尝试以下操作。然后它在一次调用中处理所有先前的行,然后从该点继续。
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)) ]
结果:
## 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