I'm looking for a vectorized solution to the following problem. There are customers that can have one of two different products, x or y, at a time. I would like to identify all rows of product x that are followed by product y for the same customer. In that case, the to_date of product x would be the same as the from_date of product y. Here is an example:
customerid = c(rep(1,2),rep(2,3))
product = c("x", "y", "x", "x", "y")
from_date = as.Date(c("2000-01-01", "2000-06-07","2001-02-01","2005-01-01","2005-11-01"))
to_date = as.Date(c("2000-06-07", "2000-10-31","2002-04-01","2005-11-01","2006-01-01"))
data.frame(customerid, product, from_date, to_date)
customerid product from_date to_date
1 1 x 2000-01-01 2000-06-07
2 1 y 2000-06-07 2000-10-31
3 2 x 2001-02-01 2002-04-01
4 2 x 2005-01-01 2005-11-01
5 2 y 2005-11-01 2006-01-01
The desired output would look like:
customerid product from_date to_date followed_by_y
1 1 x 2000-01-01 2000-06-07 yes
2 1 y 2000-06-07 2000-10-31 no
3 2 x 2001-02-01 2002-04-01 no
4 2 x 2005-01-01 2005-11-01 yes
5 2 y 2005-11-01 2006-01-01 no
My approach so far is to group the data.frame by costumerid with dplyr. But then I do not know how to check the to_date for equal values in the from_date.