使用Dplyr找出数字减少或增加的差异

4
> df
Date      User  Current_Coins
01/01      1     150
01/02      1     100
01/01      2     100
01/02      2     150
01/01      3     100
01/02      3     150
01/03      3     100
01/04      3     200
01/04      3       0

根据用户当前持有的硬币数量,我想使用dplyr总结使用和获得的硬币总数。

期望结果:

> df
User    Coins_Gained    Coins_Used
 1           0              50
 2          50               0
 3         150             250

我尝试使用lag()函数,但它不能区分使用和获得的硬币。我想不出一个优雅的解决方案,希望能得到帮助。

2个回答

6
这是一种实现方式:
library(dplyr)
df %>% 
  group_by(User) %>% 
  mutate(x = Current_Coins - lag(Current_Coins)) %>%        # compute the differences
  summarise(Coin_gained = sum(x[x>0], na.rm = TRUE),        # sum up positives
            Coin_used = abs(sum(x[x<0], na.rm = TRUE)))     # sum up negatives

#Source: local data frame [3 x 3]
#
#  User Coin_gained Coin_used
#1    1           0        50
#2    2          50         0
#3    3         150       250

3

如果您想探索使用 data.table,这里提供一种方法。我在这里使用了与 @docendo discimus 类似的策略,并使用了 shiftdata.table中的新函数)。

 library(data.table) #data.table_1.9.5
 setDT(df)[,{tmp=Current_Coins-shift(Current_Coins)
       list( Coins_gained=sum(tmp[tmp>0], na.rm=TRUE),
      Coins_Used=abs(sum(tmp[tmp<0], na.rm=TRUE)))} , User]
 #   User Coins_gained Coins_Used
 #1:    1            0         50
 #2:    2           50          0
 #3:    3          150        250

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接