2013-03-18 103 views
0

我有一个数据框与几个不同的网站鹅计数。其目的是在连续冬季的每个地点在9月至4月期间对所有8个月的 鹅进行月度计数。冬季定义为9月至4月的 之间的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)) 

其最终的情况是,有些网站的所有8项罪名在某些九月至四月期间,但在其他九月至四月期间则没有。此外,一些网站在9月至4月期间从未达到8次计数。这些玩具的数据看起来像我的实际数据:

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

我需要从不形成在九月至4月期间的连续8个计数部分数据帧中删除行。使用玩具的数据,这是我需要的数据框:

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

我试着用ddply()plyr包,但没有成功的各种命令。有没有解决这个问题的方法?

+0

你是如何定义的冬天? – 2013-03-18 09:29:05

+0

什么是<8个月计数? 8次观察或计数<8?你的输出似乎并不令人满意...... – Arun 2013-03-18 09:29:22

+0

你的问题还不够清楚,子集在R中很容易,所以请重新表达,很有可能我们很快回答你 – statquant 2013-03-18 09:33:58

回答

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]