基于非连续日期的子集数据框

Subset dataframe based of non-sequential dates

我有这样的数据

df<-data.frame(datecol=as.Date(c("2010-04-03","2010-04-04","2010-04-05","2010-04-06","2010-04-07",
                                    "2010-04-03","2010-04-04","2010-04-05","2010-04-06","2010-04-07",
                                    "2010-05-06","2010-05-07","2010-05-09","2010-06-06","2010-06-07")),x=c(1,1,1,0,1,1,1,0,0,0,1,0,0,0,1),type=c(rep("A",5),rep("B",5),rep("C",5)))

> df
      datecol x type
1  2010-04-03 1    A
2  2010-04-04 1    A
3  2010-04-05 1    A
4  2010-04-06 0    A
5  2010-04-07 1    A
6  2010-04-03 1    B
7  2010-04-04 1    B
8  2010-04-05 0    B
9  2010-04-06 0    B
10 2010-04-07 0    B
11 2010-05-06 1    C
12 2010-05-07 0    C
13 2010-05-09 0    C
14 2010-06-06 0    C
15 2010-06-07 1    C

我需要按类型对该数据框进行子集化,我只保留 "types" 具有 2 个或更多不同日期并且这些日期至少相隔 1 天。在上面的示例中,类型 A 有 4 个不同的日期,类型 C 有 2 个不同的日期,相隔超过 1 天,所以我想将这两个保存为一个新的数据框。类型 B 有 2 个不同的日期,但它们相隔不到 1 天,所以我不想保留它。

我想在一个循环中计算每种类型中有多少个唯一日期,留下超过 2 个不同日期的所有内容。然后我会查看那些只有 2 个不同日期的日期并计算它们之间的距离,只留下距离大于 1 的日期。但似乎应该有更有效的方法。有什么想法吗?

一个解决方案data.table

#make sure datecol is Date
df$datecol <- as.Date(df$datecol)

library(data.table)
#x needs to be 1 and the date difference more than a day per type
#then in the second [] we select the TRUEs
setDT(df)[x == 1, diff(datecol) > 1, by = type][V1 == TRUE, type]
#[1] A C
#Levels: A B C