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

3
我该如何根据第二列中的最大值选择重复行(仅基于第一列):
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个回答

6
您可以尝试以下方法,使用“dplyr”:

您可以尝试以下方法,使用“dplyr”:

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

谢谢,%>% 究竟是做什么的? - Soheil
@Soheil,它将一个步骤的输出传输到下一个步骤,并允许您构造一个“语句”(就像我的注释)来说明您想要做什么。 - A5C1D2H2I1M1N2O1R2T1

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接