Created
February 9, 2014 05:10
-
-
Save gghatano/8894580 to your computer and use it in GitHub Desktop.
babip (pitcher)
This file contains hidden or 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
| library(data.table) | |
| library(plyr) | |
| library(dplyr) | |
| master = fread("Master.csv") | |
| master$fullname = with(master, paste(nameFirst, nameLast)) | |
| name_id_data = with(master, data.frame(name = fullname, PIT_ID = retroID)) | |
| season_babip <- function(year){ | |
| filename = paste("all", year, ".csv", sep="") | |
| dat <- fread(filename) | |
| fields <- fread("fields.csv") | |
| setnames(dat, fields$Header) | |
| inplay_hit = c(20,21,22) | |
| # 20, 21, 22 = single, double, triple | |
| not_inplay = c(3, 23) | |
| # 3, 23 = strike out, HR | |
| setkey(dat, AB_FL) | |
| dat_AB = dat[J("T")] | |
| dat_AB$inplay_hit = with(dat_AB, ifelse(EVENT_CD %in% inplay_hit, 1, 0)) | |
| dat_AB$inplay = with(dat_AB, ifelse(EVENT_CD %in% not_inplay, 0, 1)) | |
| # calculate BABIP and avg | |
| dat_babip = dat_AB %.% group_by(PIT_ID) %.% dplyr::summarise(babip =sum(inplay_hit)/ sum(inplay), | |
| inplay_hit = sum(inplay_hit), | |
| inplay = sum(inplay), | |
| avg = sum(H_FL!=0)/ length(H_FL), | |
| hit = sum(H_FL!=0), | |
| atbat = length(H_FL) | |
| ) | |
| # make name data | |
| babip_name_data = merge(dat_babip, name_id_data, by="PIT_ID") | |
| babip_name_data$year = year | |
| return(babip_name_data) | |
| } | |
| dat = data.table() | |
| for(N in 2010:2013){ | |
| dat <- rbind.data.frame(dat, season_babip(N)) | |
| } | |
| # plot | |
| player_names = c("Yu Darvish", "Hiroki Kuroda", "Hisashi Iwakuma") | |
| player_names = c(player_names, c("Clayton Kershaw", "Bartlo Colon", "R.A. Dickey", "Cliff Lee")) | |
| subset(name_id_data, name %in% player_names) | |
| dat_pitchers = subset(dat, name %in% player_names) | |
| library(ggplot2) | |
| ggplot(data = dat_pitchers, aes(x=year, y=babip, col=name)) + geom_point(size=4) + | |
| geom_line(size=1) + ggtitle("BABIP (pitcher)") + | |
| theme(plot.title=element_text(face="bold", size=20)) | |
| ggplot(data = dat_pitchers, aes(x=year, y=avg, col=name)) + geom_point(size=4) + | |
| geom_line(size=1) + ggtitle("AVG (pitcher)") + | |
| theme(plot.title=element_text(face="bold", size=20)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment