Last active
August 29, 2015 14:27
-
-
Save bayesball/e0b5f7202cf93dec40fd to your computer and use it in GitHub Desktop.
Plots groundball statistics for all teams in a particular season
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
groundball.plot <- function(pbp, season){ | |
require(dplyr) | |
require(ggplot2) | |
require(car) | |
inplay <- filter(pbp, BATTEDBALL_CD == "F" | | |
BATTEDBALL_CD == "G" | | |
BATTEDBALL_CD == "L" | | |
BATTEDBALL_CD == "P") | |
inplay <- mutate(inplay, | |
HOME_TEAM_ID = substr(GAME_ID, 1, 3), | |
FIELD_TEAM = ifelse(BAT_HOME_ID==0, | |
as.character(HOME_TEAM_ID), | |
as.character(AWAY_TEAM_ID)), | |
BAT_TEAM = ifelse(BAT_HOME_ID==0, | |
as.character(AWAY_TEAM_ID), | |
as.character(HOME_TEAM_ID))) | |
# BB <- with(inplay, table(HOME_TEAM_ID, BATTEDBALL_CD)) | |
# with(inplay, table(BATTEDBALL_CD, EVENT_CD)) | |
# focus on EVENT_CD 2, 18, 19 (out), 20 (S), 21 (D), 22 (T), 23 (HR) | |
inplay2 <- filter(inplay, EVENT_CD != 13) | |
inplay2 <- mutate(inplay2, event=EVENT_CD) | |
inplay2$event <- recode(inplay2$event, "c(2, 18, 19)='out'; | |
20='single'; | |
21='double'; | |
22='triple'; | |
23='home run'") | |
inplay2 <- mutate(inplay2, | |
event=factor(event, c("out", "single", | |
"double", "triple", "home run")), | |
battedball=factor(BATTEDBALL_CD, | |
c("P", "G", "F", "L"), | |
c("Popup", "Groundball", "Fly Ball", "Liner"))) | |
# T.BE <- with(inplay2, table(battedball, event)) | |
# round(100 * prop.table(T.BE, 1), 1) | |
gb.data <- summarize(group_by(inplay2, FIELD_TEAM), | |
p.gb.out = sum(battedball == "Groundball" & event == "out") / | |
sum(battedball == "Groundball"), | |
p.gb = mean(battedball == "Groundball")) | |
# ggplot(gb.data, aes(p.gb.out, FIELD_TEAM)) + geom_point() | |
print(ggplot(gb.data, aes(p.gb, p.gb.out, label=FIELD_TEAM)) + | |
geom_text() + xlab("Proportion Ground Balls") + | |
ylab("Proportion of Ground Balls that are Outs") + | |
ggtitle(paste("Season =", season))) | |
data.frame(gb.data, Season=season) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment