子集数据帧

时间:2013-03-18 09:25:08

标签: r subset

我有一个数据框,其中包含几个不同地点的鹅计数。目的是每月计算鹅的数量 9月至4月期间连续冬季每个站点的所有8个月。冬季期间定义为8个月之间 九月至四月。

如果方法按计划执行,那么这就是数据的样子:

df <- data.frame(site=c(rep('site 1', 16), rep('site 2', 16), rep('site 3', 16)),
                   date=dmy(rep(c('01/09/2007', '02/10/2007', '02/11/2007', 
                              '02/12/2007', '02/01/2008',  '02/02/2008', '02/03/2008',  
                              '02/04/2008', '01/09/2008', '02/10/2008', '02/11/2008', 
                                  '02/12/2008', '02/01/2009',  '02/02/2009', '02/03/2009',  
                                  '02/04/2009'),3)),
                   count=sample(1:100, 48))

最终导致某些网站在9月至4月的某些时段都有8个计数,但在其他9月到4月期间则没有。此外,一些网站在9月至4月期间从未达到8项计数。这些玩具数据看起来像我的实际数据:

df <- df[-c(11:16, 36:48),]

我需要删除数据框中的行,这些行不是9月到4月期间8个连续计数的一部分。使用玩具数据,这是我需要的数据框架:

df <- df[-c(9:10, 27:29), ]

我使用ddply()包中的plyr尝试了各种命令但没有成功。这个问题有解决方案吗?

1 个答案:

答案 0 :(得分:3)

我能想到的一种方法是从您的约会中减去四个月,然后您可以按year进行分组。要通过减去4个月来获得相应的日期,我建议您使用mondate包。请参阅here,了解您在减去月份时遇到的问题以及如何克服这些问题时的最佳答案。

require(mondate)
df$grp <- mondate(df$date) - 4
df$year <- year(df$grp)
df$month <- month(df$date)
ddply(df, .(site, year), function(x) {
    if (all(c(1:4, 9:12) %in% x$month)) {
        return(x)
    } else {
        return(NULL)
    }
})

#      site       date count        grp year month
# 1  site 1 2007-09-01    87 2007-05-02 2007     9
# 2  site 1 2007-10-02    44 2007-06-02 2007    10
# 3  site 1 2007-11-02    50 2007-07-03 2007    11
# 4  site 1 2007-12-02    65 2007-08-02 2007    12
# 5  site 1 2008-01-02    12 2007-09-02 2007     1
# 6  site 1 2008-02-02     2 2007-10-03 2007     2
# 7  site 1 2008-03-02   100 2007-11-02 2007     3
# 8  site 1 2008-04-02    29 2007-12-03 2007     4
# 9  site 2 2007-09-01     3 2007-05-02 2007     9
# 10 site 2 2007-10-02    22 2007-06-02 2007    10
# 11 site 2 2007-11-02    56 2007-07-03 2007    11
# 12 site 2 2007-12-02     5 2007-08-02 2007    12
# 13 site 2 2008-01-02    40 2007-09-02 2007     1
# 14 site 2 2008-02-02    15 2007-10-03 2007     2
# 15 site 2 2008-03-02    10 2007-11-02 2007     3
# 16 site 2 2008-04-02    20 2007-12-03 2007     4
# 17 site 2 2008-09-01    93 2008-05-02 2008     9
# 18 site 2 2008-10-02    13 2008-06-02 2008    10
# 19 site 2 2008-11-02    58 2008-07-03 2008    11
# 20 site 2 2008-12-02    64 2008-08-02 2008    12
# 21 site 2 2009-01-02    92 2008-09-02 2008     1
# 22 site 2 2009-02-02    69 2008-10-03 2008     2
# 23 site 2 2009-03-02    89 2008-11-02 2008     3
# 24 site 2 2009-04-02    27 2008-12-03 2008     4

使用data.table的替代解决方案:

require(data.table)
require(mondate)
dt <- data.table(df)
dt[, `:=`(year=year(mondate(date)-4), month=month(date))]
dt.out <- dt[, .SD[rep(all(c(1:4,9:12) %in% month), .N)], 
           by=list(site,year)][, c("year", "month") := NULL]