2017-06-22 82 views
0

我有一个数据帧的格式dplyr条件分组日期

Account ID, Start Date, End Date 
     1 , 2016-01-01, 2016-02-01 
     1 , 2016-02-02, 2016-03-01 
     1 , 2016-03-01, 2016-04-01 
     2 , 2016-01-01, 2016-02-01 
     2 , 2016-03-02, 2016-03-20 
     2 , 2016-03-21, 2016-04-01 

我想要得到的数据帧的样子。

Account ID, Start Date, End Date 
     1 , 2016-01-01, 2016-04-01 
     2 , 2016-01-01, 2016-02-01 
     2 , 2016-03-02, 2016-04-01 

这样的,如果有一个结束日期和账户随后开始日期之间少于7天,它会合并这些成一个,并使用后者记录的结束日期和前的开始日期记录。

我已经用dplyr试验过使用Lead和Lag进行分组,但对于有3个或更多记录的帐户无效。

在该示例中,

帐户ID 1是它就会与帐户ID,和最大分组要解决的情况下,分将工作

但帐户ID 2是的情况下,将无法正常工作。

任何帮助真的很感激。

回答

2

您的数据:

dat <- read.table(text = "AccountID StartDate EndDate 
1   2016-01-01 2016-02-01 
1   2016-02-02 2016-03-01 
1   2016-03-01 2016-04-01 
2   2016-01-01 2016-02-01 
2   2016-03-02 2016-03-20 
2   2016-03-21 2016-04-01", header = TRUE, stringsAsFactors = FALSE) 
dat[2:3] <- lapply(dat[2:3], as.Date) 

可以分组后使用lag

library(dplyr) 
group_by(dat, AccountID) %>% 
    mutate(
    week = cumsum(StartDate - lag(EndDate, default = 0) > 7) 
) %>% 
    group_by(AccountID, week) %>% 
    summarize(
    StartDate = min(StartDate), 
    EndDate = max(EndDate) 
) %>% 
    ungroup() 
# # A tibble: 3 × 4 
# AccountID week StartDate EndDate 
#  <int> <int>  <date>  <date> 
# 1   1  1 2016-01-01 2016-04-01 
# 2   2  1 2016-01-01 2016-02-01 
# 3   2  2 2016-03-02 2016-04-01