Skip to contents

Turns the released plate appearances of one or many MLB games into six tidy frames that explain the result: the winner's edges in runs, the plate appearance that swung the game, the score by inning, each side's largest unanswered run and each side's top player by win probability added. It returns the same frames, column for column, as sportsdataverse-py's mlb_game_story(), and a parity test replays that function's output on real games.

A plate appearance's RE24 is the run expectancy of the base-out state after it, less the state before it, plus the runs it scored (the state after the half-inning's last plate appearance is worth 0). The state before each plate appearance is the previous one's bases and outs within the half-inning (empty, 0 outs at its start). An extra half-inning's automatic runner starts on 2nd where the plate appearances show him: after the half's first plate appearance a base is held by someone other than the batter, or (past the 9th) that plate appearance scored more runs than a home run's one, or made more outs than the batter's own.

Accounting edges are starting_pitching and bullpen: the RE24 each staff allowed, negated (runs saved against expectation); a side's starter is the first pitcher it used. Together they are the winner's batting RE24 less the loser's: the margin, less the run expectancy of an empty-base, no-out start for each half-inning the winner batted beyond the loser (a home win that skips the bottom of the 9th), so close to the margin, not equal to it.

Split edges are home_runs (value and points: the runs scored on home runs) and risp_hits (value: hits with a runner on 2nd or 3rd; points: the runs scored on those plate appearances).

The moment is the plate appearance with the largest absolute WPA (earliest on ties); with no WPA, the winner's first score after the last plate appearance it was level or behind after. The mlb_wpa release keys a plate appearance's WPA to the next one's at_bat_index, so it is moved back to the plate appearance that made it. The top performer is the player with the most WPA as batter (his side's view) and as pitcher (the other side's WPA, negated); ties go to the player with more plate appearances. The releases carry ids, not names, so player_name is NA.

The periods are innings rebuilt from the running score, so periods_agree is FALSE when the plate appearances end on another score than the schedule's final. Extra innings keep their number ("10") and are overtime.

Usage

mlb_game_story(pbp, schedule, wpa, re24)

Arguments

pbp

The plate appearances of one or many games, one row per plate appearance, from the mlb_pbp sportsdataverse-data release (https://github.com/sportsdataverse/sportsdataverse-data/releases/download/mlb_pbp/mlb_pbp_<season>.rds, or .parquet). Needs game_pk, at_bat_index, inning, half_inning, outs (after the plate appearance), home_score, away_score (after it), post_on_first_id, post_on_second_id, post_on_third_id, batter_id, pitcher_id, event and description. A plate appearance listed twice under the same game_pk and at_bat_index counts once.

schedule

The games' schedule rows, from the mlb_schedules release (.../releases/download/mlb_schedules/mlb_schedule_<season>.rds). Needs game_pk, season, home_team_id, away_team_id, home_score and away_score (the final). Keep the finished games (detailed_state "Final"); a game without both finals is dropped.

wpa

The games' win probability added, as returned by load_mlb_wpa(). Needs game_id, at_bat_index and wpa (the home win probability change).

re24

The run expectancy by base-out state for the games' seasons, as returned by load_mlb_re24_matrix(). Needs season, base_state, outs and re.

Value

A named list of six tibbles, each sorted by game_id. Only games in both pbp and schedule are kept. Rows without a game key (game_pk in pbp and schedule, game_id in wpa) are dropped with a warning. It aborts when re24 has no run expectancy for one of the games' seasons, or for a plate appearance's base-out state.

summary: one row per game.

col_nametypedescription
game_idintegerThe game's MLB Stats API game_pk.
home_team_idintegerHome team's MLB team id.
away_team_idintegerAway team's MLB team id.
home_scoreintegerHome team's final runs from the schedule.
away_scoreintegerAway team's final runs from the schedule.
winner_team_idintegerWinning team's id; NA on a tie.
loser_team_idintegerLosing team's id; NA on a tie.
marginintegerWinner's final runs less the loser's.
decidedlogicalTRUE when the game has a winner.
periods_agreelogicalTRUE when the inning sums (from the running score) equal the schedule's final; FALSE flags plate appearances that end on another score.
n_periodsintegerInnings played, extra innings included.
overtimelogicalTRUE when the game went past the 9th.

edges: one row per game and edge, ranked.

col_nametypedescription
game_idintegerThe game's game_pk.
winner_team_idintegerWinning team's id (NA on a tie).
loser_team_idintegerLosing team's id (NA on a tie).
edgecharacterEdge name. Accounting: starting_pitching, bullpen. Splits: home_runs, risp_hits.
kindcharacteraccounting for the two staffs' runs saved, which come to close to the margin; split for the overlapping run cuts.
unitcharacterAlways runs.
winner_valuedoubleWinner's value: runs saved for a staff, runs on home runs, hits with a runner in scoring position.
loser_valuedoubleLoser's value.
points_worthdoubleThe winner's runs from the edge less the loser's; positive favours the winner.
rankintegerRank of the edge within the game by points_worth, 1 = largest; equal worths keep the edge list's order.

moment: the plate appearance that swung each game.

col_nametypedescription
game_idintegerThe game's game_pk.
play_idintegerThe plate appearance's at_bat_index.
orderintegerThe same at_bat_index (the game's plate-appearance order, from 0).
periodintegerInning of the plate appearance.
clockcharacterHalf of the inning: top or bottom.
team_idintegerBatting team.
textcharacterThe plate appearance's description (else its event).
wpadoubleHome win probability after the plate appearance less before it (NA for a deciding score).
winner_wpadoubleThe same change from the winner's side (NA on a tie).
home_scoreintegerHome runs after the plate appearance.
away_scoreintegerAway runs after the plate appearance.
rulecharactermax_abs_wpa: the largest absolute WPA (earliest on ties); deciding_score where no plate appearance has one: the winner's first score after it was last level or behind, so it leads from there to the end.

periods: one row per game and inning.

col_nametypedescription
game_idintegerThe game's game_pk.
periodintegerInning, from 1.
period_labelcharacterThe inning's number ("1", ..., "10").
is_overtimelogicalTRUE for an extra inning.
home_ptsintegerHome runs in the inning: its last running score less the previous inning's.
away_ptsintegerAway runs in the inning.
home_cumintegerHome running score at the end of the inning.
away_cumintegerAway running score at the end of the inning.

runs: each side's largest unanswered run (home first).

col_nametypedescription
game_idintegerThe game's game_pk.
team_idintegerTeam that scored the runs.
pointsintegerRuns the side scored in a row with no run by the other side (a score correction stays in the run and counts against its side). Earliest on ties.
start_orderintegerat_bat_index of the run's first scoring plate appearance.
end_orderintegerat_bat_index of its last.
start_periodintegerInning of the run's first score.
end_periodintegerInning of the run's last score.
home_score_afterintegerHome score at the end of the run.
away_score_afterintegerAway score at the end of the run.

performers: each side's top player by win probability added.

col_nametypedescription
game_idintegerThe game's game_pk.
team_idintegerTeam of the top performer.
player_idintegerMLB player id.
player_namecharacterAlways NA: the releases carry ids only.
metriccharacterAlways wpa.
valuedoubleThe player's WPA for his side, as batter and pitcher (0 for every player of a game without WPA, where the most plate appearances decide).

See also

load_mlb_wpa() and load_mlb_re24_matrix() for two of the inputs.

Examples

# \donttest{
try({
  rel <- "https://github.com/sportsdataverse/sportsdataverse-data/releases/download/"
  read_release <- function(file) readRDS(gzcon(url(paste0(rel, file))))
  pbp <- read_release("mlb_pbp/mlb_pbp_2023.rds")
  sched <- read_release("mlb_schedules/mlb_schedule_2023.rds")
  sched <- sched[sched$detailed_state == "Final" & sched$game_pk == 716356, ]
  story <- mlb_game_story(pbp, sched, load_mlb_wpa(2023), load_mlb_re24_matrix(2023))
  print(story$edges)
  story$moment[, c("period", "clock", "text", "wpa")]
})
#> # A tibble: 4 × 10
#>   game_id winner_team_id loser_team_id edge     kind  unit  winner_value
#>     <int>          <int>         <int> <chr>    <chr> <chr>        <dbl>
#> 1  716356            135           145 bullpen  acco… runs          3.45
#> 2  716356            135           145 home_ru… split runs          0   
#> 3  716356            135           145 risp_hi… split runs          1   
#> 4  716356            135           145 startin… acco… runs          2.60
#> # ℹ 3 more variables: loser_value <dbl>, points_worth <dbl>, rank <int>
#> # A tibble: 1 × 4
#>   period clock text                                                  wpa
#>    <int> <chr> <chr>                                               <dbl>
#> 1     11 top   Jurickson Profar singles on a line drive to cente… -0.386
# }