Hi,
I have a challenge which I cannot deal with.
I have a df with car registrations (RegNo) and date they visited service (LastWortshopDate).
I know how to flag registrations if they include visiting a dealer within 12 months. I simply merge RegNo with a visit Month and then check repeated visits. If at least two visits are within 12 month time frame, the RegNo is flagged as Retained.Reg
data.source <- data.frame(
stringsAsFactors = FALSE,
RegNo = c("GGG","GGG","AAA","AAA",
"AAA","AAA","BBB","CCC","DDD","DDD","EEE","EEE",
"EEE","EEE","EEE","EEE","FFF","FFF","HHH","HHH","III",
"III","III","III","III","III","III","III","III"),
LastWorkshopDate = c("2018-07-04","2019-06-19",
"2020-08-03","2021-07-14","2022-04-13","2022-06-21",
"2018-01-12","2021-02-16","2021-05-09","2022-09-06",
"2018-06-13","2019-07-26","2020-07-06","2021-08-05",
"2022-07-09","2022-08-15","2018-01-09","2019-05-26",
"2018-01-09","2019-03-26","2018-06-18","2018-10-22",
"2019-04-01","2019-06-21","2019-10-21","2021-06-17",
"2022-01-12","2022-06-17","2022-10-21"),
Year = c(2018,2019,2020,2021,2022,
2022,2018,2021,2021,2022,2018,2019,2020,2021,2022,
2022,2018,2019,2018,2019,2018,2018,2019,2019,
2019,2021,2022,2022,2022),
Month = c(7,6,8,7,4,6,1,2,5,9,6,
7,7,8,7,8,1,5,1,3,6,10,4,6,10,6,1,6,10)
)
data.source
library(dplyr)
result <- data.source %>%
mutate(Month_reg = paste0(Month, RegNo)) %>%
group_by(RegNo) %>%
arrange((Month_reg))%>%
mutate(Number.of.Month_reg = row_number()) %>%
ungroup() %>%
add_count(Month_reg, name = "Same.Month.Visits") %>%
mutate(Same.Month.Visits = Same.Month.Visits) %>% mutate(
Retained.Reg = case_when(
Same.Month.Visits >1 ~ 1)) %>%
group_by(RegNo) %>%
mutate(Retained.Reg = as.numeric(any(as.logical(Retained.Reg)))) %>%
arrange(RegNo, LastWorkshopDate)
result
Now my task is to flag reg visiting not at the same month but within 9-15 months (so AAA, GGG and HHH meet this criteria) and I have no idea if that is possible in R.
It does not matter if there are multiple visits a year or not. If there are at least two visits within 9-12 months a flag should be added.
My brain is boiling and I cannot find a solution. Maybe you can?