如何根据另一个列条件删除重复的行?

时间:2015-05-09 03:25:26

标签: r duplicates

如何根据第二列中的最大值选择重复行(仅基于第一列):

data<-data.frame(a=c(1,3,3,3),b=c(1,4,6,3),d=c(1,5,7,1))

a b d
1 1 1
3 4 5
3 6 7
3 3 1


a b d
1 1 1
3 6 7

在第二列中,6是 4,6,3

之间的最大值

2 个答案:

答案 0 :(得分:6)

您可以使用&#34; dplyr&#34;:

尝试以下内容
library(dplyr)

data %>%                  ## Your data
  group_by(a) %>%         ##   grouped by "a"
  filter(b == max(b))     ##   filtered to only include the rows where b == max(b)
# Source: local data frame [2 x 3]
# Groups: a
# 
#   a b d
# 1 1 1 1
# 2 3 6 7

但请注意,如果有更多行匹配b == max(b),那么也会返回这些行。因此,替代方案可能是:

data %>%                  ## Your data
  group_by(a) %>%         ##   grouped by "a"
  arrange(desc(b)) %>%    ##   sorted by descending values of "b"
  slice(1)                ##   with just the first row extracted

答案 1 :(得分:3)

使用data.table的选项

library(data.table)
setDT(data)[, .SD[which.max(b)], a]
#   a b d
#1: 1 1 1
#2: 3 6 7

或使用.I获取行索引(这会更快一点)

 setDT(data)[data[, .I[which.max(b)], a]$V1]
 #   a b d
 #1: 1 1 1
 #2: 3 6 7

或者

setkey(setDT(data), a,b)[,.SD[.N], a]
#   a b d
#1: 1 1 1
#2: 3 6 7

如果存在最大值的关联

setDT(data)[, .SD[max(b)==b], a]
#   a b d
#1: 1 1 1
#2: 3 6 7
相关问题