Skip to content

Instantly share code, notes, and snippets.

@jalapic
Created February 17, 2016 03:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jalapic/23fce6ea0eba08ea1f34 to your computer and use it in GitHub Desktop.
Save jalapic/23fce6ea0eba08ea1f34 to your computer and use it in GitHub Desktop.
Come from behind wins
### Biggest come-from-behind title wins
library(engsoccerdata)
library(dplyr)
library(purrr)
library(ggplot2)
library(ggthemes)
head(engsoccerdata2)
df <- engsoccerdata2 %>% filter(Season!=1939 & tier==1)
df$Date <- as.Date(df$Date, format = "%Y-%m-%d")
seasons <- df$Season %>% unique
resdf<-NULL
for(j in seq_along(seasons)){
tempdf1 <- df %>% filter(Season==seasons[[j]]) %>% arrange(Date) %>% mutate(daterank = dense_rank(Date))
results<-NULL
for(i in 1:max(tempdf1$daterank)) {results[[i]] <- tempdf1[tempdf1$daterank <= i,] }
results
resdf[[j]] <- results %>%
map(maketable) %>%
map(~ mutate(., ptsbehind = max(Pts)-Pts)) %>%
Map(cbind, ., daterank=1:max(tempdf1$daterank), Season=seasons[[j]]) %>%
do.call('rbind', .) %>%
full_join( maketable(tempdf1) %>% mutate(pos = row_number()) %>% select(team, pos) ) %>%
filter(pos==1)
}
lapply(resdf, head)
resdf1 <- do.call('rbind', resdf)
head(resdf1)
resdf1 %>% arrange(-ptsbehind) %>% head(10)
# five wire-to-wire winners.
resdf1 %>%
group_by(Season) %>%
filter(ptsbehind==max(ptsbehind)) %>%
filter(daterank==max(daterank)) %>%
ungroup() %>%
arrange(-ptsbehind) %>%
data.frame()
#Sunderland 1891
df %>%
filter(Season==1891) %>%
arrange(Date) %>%
mutate(daterank = dense_rank(Date)) %>%
filter(daterank<=17) %>%
maketable
#Arsenal 1997
df %>%
filter(Season==1997) %>%
arrange(Date) %>%
mutate(daterank = dense_rank(Date)) %>%
filter(daterank<=54) %>%
maketable
#plot
resdf1 <- resdf1 %>% group_by(Season) %>% mutate(gamesfrom = GP-max(GP), teamseason = paste(team, Season+1, sep="-"))
mylevels <- resdf1 %>% arrange(Season) %>% .$teamseason %>% unique
resdf1$teamseason <- factor(resdf1$teamseason, levels=mylevels)
resdf1teams <- resdf1 %>% filter(ptsbehind>10) %>% .$teamseason %>% unique
resdf1 %>%
filter(teamseason %in% resdf1teams) %>%
group_by(teamseason, GP) %>%
filter(ptsbehind==max(ptsbehind)) %>%
filter(daterank==max(daterank)) %>%
ungroup() %>%
mutate(ptsbehind = ptsbehind * -1) %>%
ggplot(., aes(gamesfrom, ptsbehind, group=teamseason)) + geom_path(color='antiquewhite2') + facet_wrap(~teamseason) +
xlab("Games From End of Season") + ylab("Points Away from Top of Table") + theme_dark()
@jalapic
Copy link
Author

jalapic commented Feb 17, 2016

comefrombehind

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment