我正在尝试使用dplyr计算条件累积和,但遇到了麻烦。我有一个数据框,只要条件为真,就希望按组填充。请参阅以下示例:
df <- data.frame(prod = c("A", "A", "A", "A", "B", "B", "B", "B", "B"),
act = c(TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE),
sales = c(100,120, 190, 50, 30, 40, 50, 10, 30))
prod act sales
1 A TRUE 100
2 A TRUE 120
3 A TRUE 190
4 A FALSE 50
5 B TRUE 30
6 B TRUE 40
7 B FALSE 50
8 B FALSE 10
9 B FALSE 30
转到:
prod act sales cum_sales
1 A TRUE 100 100
2 A TRUE 120 220
3 A TRUE 190 410
4 A FALSE 50 410
5 B TRUE 30 30
6 B TRUE 40 70
7 B FALSE 50 70
8 B FALSE 10 70
9 B FALSE 30 70
我正在思考以下问题,但它没有用,有人有想法吗?
dfb <- df %>% group_by(prod) %>%
mutate(cum_sales = ifelse(act == TRUE, cumsum(sales), lag(sales)))
谢谢!
答案 0 :(得分:2)
由于将逻辑转换为数字,FALSE
为0,TRUE
为1,因此您可以将sales
乘以act
:
library(dplyr)
df %>% group_by(prod) %>%
mutate(cum_sales = cumsum(sales*act))
prod act sales cum_sales
<fctr> <lgl> <dbl> <dbl>
1 A TRUE 100 100
2 A TRUE 120 220
3 A TRUE 190 410
4 A FALSE 50 410
5 B TRUE 30 30
6 B TRUE 40 70
7 B FALSE 50 70
8 B FALSE 10 70
9 B FALSE 30 70
答案 1 :(得分:1)
以下是base R
df$cum_sales <- with(df, ave(sales*act, prod, FUN = cumsum))
和data.table
library(data.table)
setDT(df)[, cum_sales := sales*act, by = prod]