> 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
Based on how many coins the user currently has I want to summarize the sum of coins used and gained using dplyr.
Expected result:
> df
User Coins_Gained Coins_Used
1 0 50
2 50 0
3 150 250
I tried using lag() but doesn't separate the usage and gains in coins. I can't think of an eloquent solution to this, any help would be appreciated.
Here's one way to do it:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With