Вы можете просто установить подмножество с ave()
по специфике муниципалитета c (rev
ersed) order()
.
dat[ave(dat$Votes, dat$Municipality, FUN=function(x) rev(order(x))) <= 2, ]
# Candidates Municipality Votes
# 2 John R. A 120
# 3 Peter F. A 140
# 5 Hanna F. B 335
# 7 Andrew W. B 400
Данные:
dat <- structure(list(Candidates = structure(c(6L, 5L, 7L, 4L, 3L, 2L,
1L), .Label = c("Andrew W.", "Anthony E.", "Hanna F.", "Ignacio R.",
"John R.", "Liza S.", "Peter F."), class = "factor"), Municipality = structure(c(1L,
1L, 1L, 2L, 2L, 2L, 2L), .Label = c("A", "B"), class = "factor"),
Votes = c(100, 120, 140, 110, 335, 225, 400)), class = "data.frame", row.names = c(NA,
-7L))