也许不是最优雅的解决方案,但似乎可行。
数据:
set.seed(111)
party <- rep(LETTERS[1:2], 5)
location <- c(rep("a",2), rep("b",2),rep("c",2),rep("d",2),rep("e",2))
votes <- sample(1:100000, 10)
df <- data.frame(party, location, votes)
第 1 步:使用 aggregate 识别按位置投出的大多数选票:
most_votes <- aggregate(votes ~ location, data = df, max)
第 2 步:将most_votes 中的投票与df 中的投票相匹配,并分配诸如wins 之类的标签以识别得票最多的一方:
df$winner <- ifelse(df$votes[match(df$votes,most_votes$votes)], "wins", NA)
结果:
df
party location votes winner
1 A a 99283 wins
2 B a 27417 <NA>
3 A b 34885 wins
4 B b 6140 <NA>
5 A c 3117 <NA>
6 B c 29258 wins
7 A d 84249 <NA>
8 B d 90875 wins
9 A e 86641 wins
10 B e 18567 <NA>