I have some time-series data resembling the following:
df <- data.frame(id = c("001","001","001","002", "003","003","003","003",
"004","004","004","005"),
year_mon = c(2021-01, 2021-02, 2021-03, 2021-01, 2021-01, 2021-05, 2021-06,
2021-08, 2021-03, 2021-04, 2021-07, 2021-08),
value = c(15, 20, 25, 30, 19, 17, 18, 21, 39, 45, 21, 10))
id year_mon value
001 2021-01 15
001 2021-02 20
001 2021-03 25
002 2021-01 30
003 2021-01 19
003 2021-05 17
003 2021-06 18
003 2021-08 21
004 2021-03 39
004 2021-04 45
004 2021-07 21
005 2021-08 10
I want to lag 'value' by 1 month for each id. However, in the year_mon column there are some missing dates.
I tried doing:
new_df <- df %>%
arrange(id, year_mon) %>%
group_by(id) %>%
mutate(lag_value = lag(value, 1L))
But this is returning values from the previous row, rather than the previous month. How do I do it so that the data output is:
id year_mon value lag_value
001 2021-01 15 NA
001 2021-02 20 15
001 2021-03 25 20
002 2021-01 30 NA
003 2021-01 19 NA
003 2021-05 17 NA
003 2021-06 18 17
003 2021-08 21 NA
004 2021-03 39 NA
004 2021-04 45 39
004 2021-07 21 NA
005 2021-08 10 NA
Whereby an NA is returned if the month in year_mon is not -1 month.