【发布时间】:2020-03-29 23:28:14
【问题描述】:
我正在寻找以下问题的矢量化解决方案。有些客户可以同时拥有两种不同的产品 x 或 y 中的一种。我想为同一客户识别产品 x 后跟产品 y 的所有行。在这种情况下,产品 x 的 to_date 将与产品 y 的 from_date 相同。这是一个例子:
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
所需的输出如下所示:
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
到目前为止,我的方法是使用 dplyr 按costumerid 对 data.frame 进行分组。但是后来我不知道如何检查to_date 中from_date 中的相等值。
【问题讨论】:
标签: r