data(cars)

head(cars)
##   speed dist
## 1     4    2
## 2     4   10
## 3     7    4
## 4     7   22
## 5     8   16
## 6     9   10
median(cars[,1])
## [1] 15
library(rvest)

url <- "https://en.wikipedia.org/wiki/Player_efficiency_rating"

tables <- read_html(url) |> html_table()

per <- Filter(function(x) "PER" %in% names(x), tables)[[1]]

head(per)
## # A tibble: 6 × 5
##    Rank Player            Pos   `Team(s) played for (years)[a]`              PER
##   <int> <chr>             <chr> <chr>                                      <dbl>
## 1     1 Nikola Jokić^     C     "Denver Nuggets (2015–present)"             28.8
## 2     2 Joel Embiid^      C     "Philadelphia 76ers (2014–present)"         28.0
## 3     3 Michael Jordan*   SG    "Chicago Bulls (1984–1993, 1995–1998)Wash…  27.9
## 4     4 LeBron James^     SF    "Cleveland Cavaliers (2003–2010, 2014–201…  26.7
## 5     5 Anthony Davis^    PF/C  "New Orleans Hornets/Pelicans (2012–2019)…  26.7
## 6     6 Shaquille O'Neal* C     "Orlando Magic (1992–1996)Los Angeles Lak…  26.4

Q3 Finding Hidden Value in MLB Pitching

Identify pitchers whose 2024 ERA was worse than their underlying performance suggests. This historical analysis prepares data for future scouting analysis and a Tableau dashboard.

Research questions

  1. Which pitchers have the largest differences between ERA and expected ERA?
  2. How closely are ERA and expected ERA related?
  3. Do pitchers with higher strikeout-minus-walk rates have lower expected ERA?
  4. Which pitchers have promising underlying performance despite a higher ERA?
  5. Does increasing the minimum innings requirement change the scouting list?

1. Extract the data

I use two public MLB sources: Baseball Savant’s expected statistics and MLB’s season pitching totals. Both cover the 2024 regular season. Player IDs allow the datasets to be joined without matching names.

library(jsonlite)
library(knitr)

savant_url <- paste0(
  "https://baseballsavant.mlb.com/leaderboard/expected_statistics",
  "?type=pitcher&year=2024&min=1&csv=true"
)

mlb_url <- paste0(
  "https://statsapi.mlb.com/api/v1/stats",
  "?stats=season&group=pitching&season=2024",
  "&sportIds=1&playerPool=ALL&limit=5000"
)

if (!file.exists("savant_2024.csv")) {
  download.file(savant_url, "savant_2024.csv", mode = "wb")
}

if (!file.exists("mlb_2024.json")) {
  download.file(mlb_url, "mlb_2024.json", mode = "wb")
}

savant <- read.csv("savant_2024.csv", fileEncoding = "UTF-8-BOM")
response <- fromJSON("mlb_2024.json")
mlb <- response$stats$splits[[1]]

# Confirm that the API returned all available records.
stopifnot(nrow(mlb) == response$stats$totalSplits[1])

data.frame(
  Source = c("Baseball Savant", "MLB Stats API"),
  Rows = c(nrow(savant), nrow(mlb))
)
##            Source Rows
## 1 Baseball Savant  855
## 2   MLB Stats API  855

2. Describe and select the data

Each dataset contains one row per pitcher for the season, including pitchers with very little playing time.

From Savant, I keep expected ERA (xera) and batted-ball count (bip). From MLB, I keep observed ERA, workload, strikeouts and walks.

Sources:

expected <- data.frame(
  player_id = savant$player_id,
  xera = savant$xera,
  bip = savant$bip
)


era <- mlb$stat$era
era[era == "-.--"] <- NA

traditional <- data.frame(
  player_id = mlb$player$id,
  player_name = mlb$player$fullName,
  era = as.numeric(era),
  outs = mlb$stat$outs,
  batters_faced = mlb$stat$battersFaced,
  strikeouts = mlb$stat$strikeOuts,
  walks = mlb$stat$baseOnBalls
)

str(expected)
## 'data.frame':    855 obs. of  3 variables:
##  $ player_id: int  657277 607625 605400 669302 554430 621244 669203 669923 656605 641154 ...
##  $ xera     : num  4.34 3.75 3.75 3.06 2.75 4.68 3.29 3.39 4.22 3.7 ...
##  $ bip      : int  617 598 570 542 503 565 553 568 540 523 ...
str(traditional)
## 'data.frame':    855 obs. of  7 variables:
##  $ player_id    : int  657193 669456 623520 665828 650489 687847 669395 674444 656353 622766 ...
##  $ player_name  : chr  "Eddy Alvarez" "Shane Bieber" "David Bote" "Oswaldo Cabrera" ...
##  $ era          : num  0 0 0 0 0 0 0 0 0 0 ...
##  $ outs         : int  3 36 3 1 4 3 3 17 14 3 ...
##  $ batters_faced: int  5 45 5 3 4 4 4 18 19 3 ...
##  $ strikeouts   : int  1 20 0 0 0 1 1 4 1 0 ...
##  $ walks        : int  0 1 1 2 0 0 1 0 2 0 ...

3. Clean and join

The join uses MLB player IDs, not names. These files contain season totals across teams, so traded pitchers should not be counted twice.

Missing performance values remain missing. I exclude them from analysis rather than replace them with zero.

stopifnot(
  !anyNA(expected$player_id),
  !anyNA(traditional$player_id),
  !anyDuplicated(expected$player_id),
  !anyDuplicated(traditional$player_id)
)


sum(!expected$player_id %in% traditional$player_id)
## [1] 0
sum(!traditional$player_id %in% expected$player_id)
## [1] 0
pitchers <- merge(expected, traditional, by = "player_id")


colSums(is.na(pitchers))
##     player_id          xera           bip   player_name           era 
##             0             1             0             0             2 
##          outs batters_faced    strikeouts         walks 
##             0             0             0             0

4. Create useful variables

I required at least 50 innings and 100 batted balls

pitchers$innings <- pitchers$outs / 3
pitchers$era_gap <- pitchers$era - pitchers$xera
pitchers$k_bb_pct <- 100 *
  (pitchers$strikeouts - pitchers$walks) / pitchers$batters_faced

clean <- pitchers[complete.cases(pitchers), ]
clean <- subset(clean, innings >= 50 & bip >= 100)

stopifnot(
  nrow(clean) > 0,
  all(clean$batters_faced > 0),
  all(clean$strikeouts + clean$walks <= clean$batters_faced)
)

data.frame(
  Joined_rows = nrow(pitchers),
  Analysis_rows = nrow(clean),
  Excluded_rows = nrow(pitchers) - nrow(clean)
)
##   Joined_rows Analysis_rows Excluded_rows
## 1         855           351           504
summary(clean[c("innings", "era", "xera", "era_gap", "k_bb_pct")])
##     innings            era             xera          era_gap        
##  Min.   : 50.00   Min.   :0.610   Min.   :1.780   Min.   :-2.75000  
##  1st Qu.: 61.00   1st Qu.:3.200   1st Qu.:3.390   1st Qu.:-0.59000  
##  Median : 74.33   Median :3.790   Median :3.970   Median :-0.15000  
##  Mean   : 97.58   Mean   :3.898   Mean   :3.973   Mean   :-0.07479  
##  3rd Qu.:134.83   3rd Qu.:4.495   3rd Qu.:4.490   3rd Qu.: 0.39500  
##  Max.   :208.67   Max.   :8.520   Max.   :7.160   Max.   : 2.71000  
##     k_bb_pct      
##  Min.   :-0.2475  
##  1st Qu.:11.8167  
##  Median :14.7567  
##  Mean   :15.2576  
##  3rd Qu.:18.3112  
##  Max.   :33.3333

6. Export

clean$season <- 2024

write.csv(clean, "pitchers_2024_clean.csv", row.names = FALSE)