nemja
nemja

Reputation: 499

getting difference for variable per year

I would like to get the difference for consecutive years in a data frame like this:

    group year value
    1     2017 10
    1     2018 20
    1     2019 25
    2     2017 5
    2     2018 10
    2     2019 15 

If I use the following code I cannot get the right years to allign for the difference.

    df%>% 
      group_by(group) %>% 
      summarise(difference= abs(diff(value)))

How do I include the year so that I get the difference for the group per year?

Upvotes: 0

Views: 55

Answers (1)

Aleksandr
Aleksandr

Reputation: 1914

library(dplyr)

# Creating a data frame
df <- data.frame(
  group = c(1, 1, 1, 2, 2, 2),
  year = c(2017, 2018, 2019, 2017, 2018, 2019),
  value = c(10, 20, 25, 5, 10, 15)
)

# get nominal differences
diffs <- df %>% 
  group_by(group) %>% 
  arrange(year) %>% 
  mutate(difference = value - lag(value)) %>% 
  ungroup %>% 
  arrange(group)

diffs

Upvotes: 1

Related Questions