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

时间:2017-08-17 23:09:08

标签: r date conditional-statements subset plyr

我的数据看起来像这样

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

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

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

1 个答案:

答案 0 :(得分:2)

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
相关问题