删除多个重复集并保留一个

时间:2013-12-28 15:36:24

标签: r duplicates

我有多个id -date集副本,并希望删除除第一个之外的所有重复集。我怎么能这样做?论坛上没有一个例子为我的案例提供了一个有效的例子。根据提供的输出数据,我希望保留以下内容:

1     767 10-dec-97   1
2     767 10-dec-97   2
3     767 10-dec-97   3
4     767 10-dec-97   4
9   19025 11-dec-97   1
10  19025 11-dec-97   2
11  19025 11-dec-97   3
18  27452 16-apr-95   1
19  27452 16-apr-95   2
20  27452 16-apr-95   3
21  27452 16-apr-95   4

示例数据如下:

structure(list(id = c(767L, 767L, 767L, 767L, 9271L, 9271L, 9271L, 
9271L, 19025L, 19025L, 19025L, 162749L, 162749L, 162749L, 183446L, 
183446L, 183446L, 27452L, 27452L, 27452L, 27452L, 84002L, 84002L, 
84002L, 84002L, 276172L, 276172L, 276172L, 276172L), date = c("10-dec-97", 
"10-dec-97", "10-dec-97", "10-dec-97", "10-dec-97", "10-dec-97", 
"10-dec-97", "10-dec-97", "11-dec-97", "11-dec-97", "11-dec-97", 
"11-dec-97", "11-dec-97", "11-dec-97", "11-dec-97", "11-dec-97", 
"11-dec-97", "16-apr-95", "16-apr-95", "16-apr-95", "16-apr-95", 
"16-apr-95", "16-apr-95", "16-apr-95", "16-apr-95", "16-apr-95", 
"16-apr-95", "16-apr-95", "16-apr-95"), seq = c(1L, 2L, 3L, 4L, 
1L, 2L, 3L, 4L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 
4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L)), datalabel = "", time.stamp = "28 Dec 2013 16:22", .Names = c("id", 
"date", "seq"), formats = c("%8.0g", "%9s", "%8.0g"), types = c(253L, 
9L, 251L), val.labels = c("", "", ""), var.labels = c("", "", 
""), row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", 
"10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", 
"21", "22", "23", "24", "25", "26", "27", "28", "29"), version = 12L, class = "data.frame")

3 个答案:

答案 0 :(得分:5)

df[!duplicated(df[,c("date", "seq")]),]

      id      date seq
1    767 10-dec-97   1
2    767 10-dec-97   2
3    767 10-dec-97   3
4    767 10-dec-97   4
9  19025 11-dec-97   1
10 19025 11-dec-97   2
11 19025 11-dec-97   3
18 27452 16-apr-95   1
19 27452 16-apr-95   2
20 27452 16-apr-95   3
21 27452 16-apr-95   4

答案 1 :(得分:4)

library(data.table)

dt <- data.table(df)
setkeyv(dt, c('date','seq'))
unique(dt)

输出 -

       id      date seq
 1:   767 10-dec-97   1
 2:   767 10-dec-97   2
 3:   767 10-dec-97   3
 4:   767 10-dec-97   4
 5: 19025 11-dec-97   1
 6: 19025 11-dec-97   2
 7: 19025 11-dec-97   3
 8: 27452 16-apr-95   1
 9: 27452 16-apr-95   2
10: 27452 16-apr-95   3
11: 27452 16-apr-95   4

答案 2 :(得分:3)

以下是使用aggregatehead的基础解决方案:

aggregate(.~seq+date, data=x, FUN=head, 1)
   seq      date    id
1    1 10-dec-97   767
2    2 10-dec-97   767
3    3 10-dec-97   767
4    4 10-dec-97   767
5    1 11-dec-97 19025
6    2 11-dec-97 19025
7    3 11-dec-97 19025
8    1 16-apr-95 27452
9    2 16-apr-95 27452
10   3 16-apr-95 27452
11   4 16-apr-95 27452

[也可以用作aggregate的函数,结果相同:

aggregate(.~seq+date, data=x, FUN='[', 1)