使用dplyr 的一种方法是:
library(dplyr)
foo %>%
#For each Class
group_by(Class) %>%
# Sort rows in descending way using x3: you get the max x3 value on top
# for each group
arrange(desc(x3)) %>%
# Select the first row for each Class
slice(1)
# Class x2 x3 x4
#1 A 16 49 20
#2 B 78 21 48
编辑
鉴于@Ananda 的 tie-values 考虑和他在评论中的建议,
你也可以做这样的事情。但是,@Richard Acriven 的想法是
走的路,如果有关系。
# Data
foo2 <- structure(list(Class = structure(c(1L, 1L, 1L, 2L, 2L), .Label = c("A",
"B"), class = "factor"), x2 = c(14L, 8L, 16L, 78L, 8L), x3 = c(49L,
18L, 49L, 21L, 18L), x4 = c(53L, 17L, 20L, 48L, 5L)), .Names = c("Class",
"x2", "x3", "x4"), class = "data.frame", row.names = c(NA, -5L
))
# Class x2 x3 x4
#1 A 14 49 53
#2 A 8 18 17
#3 A 16 49 20
#4 B 78 21 48
#5 B 8 18 5
foo2 %>%
group_by(Class) %>%
mutate(Rank = dense_rank(desc(x3))) %>%
filter(Rank == 1)
# Class x2 x3 x4 Rank
#1 A 14 49 53 1
#2 A 16 49 20 1
#3 B 78 21 48 1