Skip to content

Instantly share code, notes, and snippets.

@bayesball
Created October 3, 2024 11:13
Show Gist options
  • Save bayesball/f61a6c7ac762442f01a6696962e81303 to your computer and use it in GitHub Desktop.
Save bayesball/f61a6c7ac762442f01a6696962e81303 to your computer and use it in GitHub Desktop.
R function to obtain MLB standings for a particular season between two dates
get_standings <- function(s_date, e_date){
require(sabRmetrics)
require(dplyr)
Teams <- c("Chicago White Sox", "Cleveland Guardians",
"Detroit Tigers", "Kansas City Royals",
"Minnesota Twins", "Baltimore Orioles",
"Boston Red Sox", "New York Yankees",
"Tampa Bay Rays", "Toronto Blue Jays",
"Houston Astros", "Los Angeles Angels",
"Oakland Athletics", "Seattle Mariners",
"Texas Rangers", "Chicago Cubs",
"Cincinnati Reds", "Milwaukee Brewers",
"Pittsburgh Pirates", "St. Louis Cardinals",
"Atlanta Braves", "Miami Marlins",
"New York Mets", "Philadelphia Phillies",
"Washington Nationals", "Arizona Diamondbacks",
"Colorado Rockies", "Los Angeles Dodgers",
"San Diego Padres", "San Francisco Giants")
Division <- c(rep("AL CENTRAL", 5),
rep("AL EAST", 5),
rep("AL WEST", 5),
rep("NL CENTRAL", 5),
rep("NL EAST", 5),
rep("NL WEST", 5))
teams <- data.frame(Team = Teams,
Division = Division) |>
mutate(League = substr(Division, 1, 2))
game_results <- sabRmetrics::extract_schedule(
start_date = s_date,
end_date = e_date)
game_results |>
mutate(Winner = ifelse(score_home > score_away,
team_name_home, team_name_away),
Loser = ifelse(score_home < score_away,
team_name_home, team_name_away)
) -> game_results
game_results |>
group_by(Winner) |>
summarize(W = n()) -> wins
game_results |>
group_by(Loser) |>
summarize(L = n()) -> losses
wins_losses <- inner_join(wins, losses,
by = c("Winner" = "Loser")) |>
rename(Team = Winner)
inner_join(wins_losses, teams, by = "Team" ) |>
mutate(Begin = s_date,
End = e_date) |>
arrange(League, Division, desc(W)) |>
select(Team, Division, Begin, End, W, L)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment