基于日期范围的不同行

时间:2015-04-09 11:10:15

标签: r dplyr

我有一个大型数据集,其结构类似于以下内容:

structure(list(pathogen = c("MRSA", "L. pneumophila", "MRSA", 
"L. pneumophila", "MRSA", "MRSA", "MRSA", "L. pneumophila", "L. pneumophila", 
"MRSA"), variant = c("mecA", "sg1", "mecA", "sg1", "mecA", "mecC", 
"mecA", "sg1", "sg6", "mecA"), n = c(25L, 14L, 235L, 2L, 64L, 
15L, 13L, 6L, 11L, 8L), date = structure(c(15156, 15248, 15279, 
15279, 15309, 15340, 15340, 15400, 15431, 15461), class = "Date")), .Names = c("pathogen", 
"variant", "n", "date"), row.names = c(NA, -10L), class = "data.frame")

我想找到每行中包含前一个x月期间未记录的变量组合。因此,当我查找前{3}中未记录的pathogenvariant的组合时,我会从以下地址开始:

         pathogen variant   n       date
1            MRSA    mecA  25 2011-07-01
2  L. pneumophila     sg1  14 2011-10-01
3            MRSA    mecA 235 2011-11-01
4  L. pneumophila     sg1   2 2011-11-01
5            MRSA    mecA  64 2011-12-01
6            MRSA    mecC  15 2012-01-01
7            MRSA    mecA  13 2012-01-01
8  L. pneumophila     sg1   6 2012-03-01
9  L. pneumophila     sg6  11 2012-04-01
10           MRSA    mecA   8 2012-05-01

为:

         pathogen variant   n       date
1            MRSA    mecA  25 2011-07-01
2  L. pneumophila     sg1  14 2011-10-01
3            MRSA    mecA 235 2011-11-01
6            MRSA    mecC  15 2012-01-01
8  L. pneumophila     sg1   6 2012-03-01
9  L. pneumophila     sg6  11 2012-04-01
10           MRSA    mecA   8 2012-05-01

到目前为止,我所考虑的所有解决方案都涉及编写循环。我也尝试尽可能多地使用dplyr进行分析,所以我的问题是:这在dplyr中是否可行?如果没有,R-ish方法会是什么样的?< / p>

1 个答案:

答案 0 :(得分:3)

我不确定处理确切月份间隔的最佳方法,但为了让您开始,您可以按如下方式计算天数差异(导致问题中显示的输出相同):

df %>%
  group_by(pathogen, variant) %>%
  filter(c(TRUE, diff(date) > 90))   # check for difference of 90 days
#Source: local data frame [7 x 4]
#Groups: pathogen, variant
#
#        pathogen variant   n       date
#1           MRSA    mecA  25 2011-07-01
#2 L. pneumophila     sg1  14 2011-10-01
#3           MRSA    mecA 235 2011-11-01
#4           MRSA    mecC  15 2012-01-01
#5 L. pneumophila     sg1   6 2012-03-01
#6 L. pneumophila     sg6  11 2012-04-01
#7           MRSA    mecA   8 2012-05-01