2017-03-09 86 views
0

我試圖用dplyr計算一個有條件的累積和,但遇到了麻煩。只要條件成立,我就有一個數據框,並且希望按羣組合並。請看下面的例子:有條件的累積和與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))) 

謝謝!

回答

2

由於轉換的邏輯,以數字給出了和1,你可以簡單地通過actsales

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 
+0

非常簡單,謝謝! – tonyk

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]