title: “hawkmlblab” output: html_document date: “2026-04-17”
############################################################
## 1. Check for Required Packages and Install if Missing
############################################################
# Check for Lahman (historical MLB data)
if (!requireNamespace("Lahman", quietly = TRUE)) {
install.packages("Lahman")
}
# Check for tidyverse
if (!requireNamespace("tidyverse", quietly = TRUE)) {
install.packages("tidyverse")
}
############################################################
## 2. Load Required Packages
############################################################
library(Lahman)
library(tidyverse)
############################################################
## 3. Define the Season of Interest
############################################################
# Most recently completed MLB season
season_year <- 2025
############################################################
## 4. Pull Season-Level Batting Data (Lahman)
############################################################
# The Batting table contains one row per player per season per team
batting_data <- Batting %>%
filter(yearID == season_year)
############################################################
## 5. Inspect and Filter the Data
############################################################
# Calculate plate appearances (AB + BB + HBP + SF)
qualified_hitters <- batting_data %>%
mutate(
PA = AB + BB + HBP + SF
) %>%
filter(PA >= 400)
############################################################
## 6. Summarize: Identify the Top Home Run Hitters
############################################################
# Players may appear multiple times if traded; combine them
hr_leaders <- qualified_hitters %>%
group_by(playerID) %>%
summarise(
HR = sum(HR),
PA = sum(PA),
.groups = "drop"
) %>%
arrange(desc(HR)) %>%
slice_head(n = 10) %>%
left_join(People, by = "playerID") %>%
mutate(
Name = paste(nameFirst, nameLast)
) %>%
select(Name, PA, HR)
############################################################
## 7. Create the Visualization
############################################################
HRPlot <- ggplot(hr_leaders,
aes(x = reorder(Name, HR), y = HR)) +
geom_col(fill = "firebrick") +
coord_flip() +
labs(
title = "Top 10 MLB Home Run Hitters",
subtitle = "2025 Regular Season (Minimum 400 PA)",
x = "Player",
y = "Home Runs",
caption = "Source: Lahman Baseball Database"
) +
theme_minimal()
HRPlot
############################################################
## 8. Optional Extension Ideas (Not Executed)
############################################################
#
# - Compare HR with RBI or runs scored
# - Summarize by teamID
# - Compute HR per PA (rate stat)
# - Compare two seasons side by side
#
############################################################