我想删除列a b具有相同值的行。此外,唯一行应包含重复项的最新日期(列c)。例如:
> a <- c(rep("A", 3), rep("B", 3), rep("C",2))
> b <- c(1,1,2,4,1,1,2,2)
> c <- c("2016-10-01", "2016-10-02", "2016-10-03", "2016-10-04", "2016-10-04", "2016-10-05", "2016-10-06", "2016-10-07")
> df <-data.frame(a,b,c)
> df
a b c
1 A 1 2016-10-01
2 A 1 2016-10-02
3 A 2 2016-10-03
4 B 4 2016-10-04
5 B 1 2016-10-04
6 B 1 2016-10-05
7 C 2 2016-10-06
8 C 2 2016-10-07
我想获得以下数据框:
a b c
1 A 1 2016-10-02
3 A 2 2016-10-03
4 B 4 2016-10-04
5 B 1 2016-10-05
6 C 2 2016-10-07
这是我到目前为止所尝试的内容:
> df[!(duplicated(df$a, df$b)|
+ duplicated(df$a, df$b, fromLast=TRUE)),]
a b c
1 A 1 2016-10-01
2 A 1 2016-10-02
3 A 2 2016-10-03
4 B 4 2016-10-04
5 B 1 2016-10-04
6 B 1 2016-10-05
答案 0 :(得分:1)
您首先要排序,然后进行选择。
df <- df[ order(df[['c']]), ]
small_df <- df[ !duplicated(df[c('a','b')], fromLast=TRUE)), ]
答案 1 :(得分:0)
你可以简单地拥有:
df$c <- as.character(df$c)
aggregate(c~a+b, df, max)
a b c
1 A 1 2016-10-02
2 B 1 2016-10-05
3 A 2 2016-10-03
4 C 2 2016-10-07
5 B 4 2016-10-04