2017-06-22 85 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