方式一:
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
編輯 鑑於@阿南達的領帶值考慮,他在評析的建議, 你可以做這樣的事情爲好。但是,@理查德·阿克爾文的想法是,如果有聯繫的話,那麼這條路就是 。
# 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
您在預計結果的情況下會有什麼結果?即如果在第x3欄中第一個和第三個條目都是49? – 2014-11-06 07:11:13