Created
January 19, 2017 10:57
-
-
Save Keiku/4c81cb3b95bf6a12aea212801831f549 to your computer and use it in GitHub Desktop.
Calculate elapsed months.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(dplyr) | |
library(lubridate) | |
df <- data_frame( | |
id = c(1, 1, 1, 2, 2, 2), | |
ym = c("201512", "201601", "201603", "201512", "201602", "201603") | |
) | |
elapsed_months <- function(end, start) { | |
12 * (year(end) - year(start)) + (month(end) - month(start)) | |
} | |
df %>% | |
mutate(ymd = ymd(paste0(ym, "01"))) %>% | |
group_by(id) %>% | |
mutate( | |
lag = elapsed_months(ymd, lag(ymd)), | |
ymd = NULL | |
) | |
# Source: local data frame [6 x 3] | |
# Groups: id [2] | |
# | |
# id ym lag | |
# <dbl> <chr> <dbl> | |
# 1 1 201512 NA | |
# 2 1 201601 1 | |
# 3 1 201603 2 | |
# 4 2 201512 NA | |
# 5 2 201602 2 | |
# 6 2 201603 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment