I am trying to create a list in R of baseball players with the most hits in a year for the past 30+ years but I need there to be a tiebreaker in case two players have the same number of hits. I am currently using a formula like
mosthits <- merge(aggregate(hits ~ year, data=battingstats, max), battingstats, all.x=T)
but this doesn't take ties into account. How can I create a tiebreaker such as which of the players had the most home runs in that season?
Using dplyr
, we can sort by hits and then by homeruns, and then keep the top row for each year:
library(dplyr)
battingstats %>%
arrange(year, desc(hits), desc(homeruns)) %>%
group_by(year) %>%
slice(1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.