Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the differences depending if a number is decreased or increased with Dplyr

Tags:

r

dplyr

> 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.

like image 334
ant Avatar asked Jan 09 '23 02:01

ant


1 Answers

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
like image 132
talat Avatar answered Jan 11 '23 19:01

talat