我正在编写一些代码来创建库存前滚,其中客户的期末余额不能低于零,但无法在R:中找到实现这一点的方法
ID | |||||||||
---|---|---|---|---|---|---|---|---|---|
A | A | A | A | A |
library(tidyverse)
df1 %>%
group_by(ID) %>%
mutate(EndBal = unlist(
accumulate2(c(0, Used), Purchased, ~..1 - ..2 + ..3)[-1]),
BegBal = lag(EndBal, default = 0))
ID Purchased Used EndBal BegBal
<chr> <int> <int> <dbl> <dbl>
1 A 3 1 2 0
2 A 0 1 1 2
3 A 0 1 0 1
4 A 0 0 0 0
5 A 2 1 1 0
df1 <- structure(list(ID = c("A", "A", "A", "A", "A"),
Purchased = c(3L, 0L, 0L, 0L, 2L),
Used = c(1L, 1L, 1L, 0L, 1L)), row.names = c(NA, -5L), class = "data.frame")
我使用了Onyambu发布的修改版本:
df1 <- structure(list(ID = c("A", "A", "A", "A", "A", "A"),
Purchased = c(3L, 0L, 0L, 0L, 0L, 2L)),
row.names = c(NA, -6L), class = "data.frame")
df2 <- df1 %>%
group_by(ID) %>%
mutate(EndBal = unlist(
accumulate(Purchased, ~..1 + ..2 - ifelse(..1 + ..2 > 0,1,0))),
BegBal = lag(EndBal, default = 0))
唯一的问题是它返回的EndBal值对于第一个记录来说太高了1