Skip to content

Instantly share code, notes, and snippets.

@bayesball
Created April 6, 2014 20:35
Show Gist options
  • Select an option

  • Save bayesball/10011176 to your computer and use it in GitHub Desktop.

Select an option

Save bayesball/10011176 to your computer and use it in GitHub Desktop.
The First Pitch Effect
##########################################
# the first pitch effect
# preview of Chapter 7 material in ABDWR
##########################################
# load in Retrosheet 2013 play-by-play data
# (have to download Retrosheet data and add run values)
load("pbp2013.Rdata")
# restrict attention to batting plays
d2013 <- subset(d2013, BAT_EVENT_FL==TRUE)
# remove pickoff throws, etc from pitch sequence variable
d2013$pseq <- gsub("[.>123N+*]", "", d2013$PITCH_SEQ_TX)
# First.Pitch variable records outcome of first pitch
d2013$First.Pitch <- substr(d2013$pseq, 1, 1)
# Count variable records if the first pitch count is 0-1, 1-0 or
# the plate appearance is over (hit by pitch or ball hit in play)
d2013$Count <- ifelse(d2013$First.Pitch %in%
c("C", "F", "L", "M", "O", "Q", "S", "T"),
"0-1", ifelse(d2013$First.Pitch %in% c("B", "I", "P"),
"1-0", "End.PA"))
# find sample size, mean, and sd of run values for
# the plate appearances for each possibility (0-1, 1-0, or End.PA)
with(d2013, c(N=length(RUNS.VALUE),
Mean=mean(RUNS.VALUE),
SD=sd(RUNS.VALUE)))
library(dplyr)
S <- summarize(group_by(d2013, Count),
N=length(RUNS.VALUE),
Mean=mean(RUNS.VALUE),
SD=sd(RUNS.VALUE))
S
# graph error bars of the run values for each
# first pitch outcome
library(ggplot2)
limits <- aes(ymin=Mean - SD, ymax=Mean + SD)
ggplot(S, aes(Count, Mean)) +
geom_point(size=6, color="red") +
geom_pointrange(limits, color="red", size=1.5) +
geom_hline(xintercept=0, color="blue") +
labs(title="The First Pitch Effect")+
ylab("Run Value") +
xlab("Outcome of First Pitch") +
theme(axis.text = element_text(size = rel(2))) +
theme(axis.title = element_text(size = rel(2))) +
theme(plot.title = element_text(size = rel(2)))
##################################################
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment