Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Bottom 3 at Christmas Survive
### Have bottom 3 at Christmas all survived?
library(engsoccerdata)
library(tidyverse)
df <- rbind(england, england_current()) %>% filter(tier==1)
df.seasons <- split(df, df$Season)
df.tables <- lapply(df.seasons, function(x) maketable_eng(x, tier=1, Season = x[1,2]))
df.tables <- Map(cbind, df.tables, Season=unique(df$Season))
lubridate::yday("2015-12-25") #359
lubridate::yday("2016-12-25") #360
lubridate::yday("2016-07-01") #183
# work out day of year
df$yday <- ifelse(lubridate::leap_year(df$Date), lubridate::yday(df$Date), lubridate::yday(df$Date)-1)
dfxmas <- df %>% group_by(Season) %>% filter(yday>183 & yday<=359)
dfxmas.seasons <- split(dfxmas, dfxmas$Season)
#doing as loop rather than lapply - as something funny about my function maketable that I need to fix with dates
dfxmas.tables=NULL
for(i in 1:length(unique(df$Season))){
dfxmas.tables[[i]]<- maketable_eng(dfxmas.seasons[[i]],tier=1, Season=unique(df$Season)[i])
}
dfxmas.tables <- Map(cbind, dfxmas.tables, Season=unique(dfxmas$Season))
dfxmas.tables.x <- do.call('rbind', dfxmas.tables) %>%
group_by(Season) %>%
mutate(Posxmas = as.numeric(Pos),
numteams = max(Posxmas)) %>%
mutate(bottom3xmas = ifelse(Posxmas>=(max(Posxmas)-2),T,F))
df.tables.x <- do.call('rbind', df.tables) %>%
group_by(Season) %>%
mutate(Pos = as.numeric(Pos),
numteams = max(Pos)) %>%
mutate(bottom3 = ifelse(Pos>=(max(Pos)-2),T,F))
head(dfxmas.tables.x)
head(df.tables.x)
df.tables.x %>% select(team, Season,numteams, bottom3, Pos) %>%
full_join(
dfxmas.tables.x %>% select(team, Season,numteams, bottom3xmas, Posxmas)
) -> df.all
head(df.all,12)
df.all %>%
group_by(Season,team) %>%
mutate(didnt_escape = sum(bottom3+bottom3xmas)) %>%
group_by(Season) %>%
summarise(didnt_escape_total = sum(didnt_escape==2)) %>%
filter(didnt_escape_total==0)
#1937,1982,1986
which(unique(df$Season) %in% c(1937,1982,1986)) #[1] 46 84 88
dfxmas.tables[[46]] #Everton, Blackpool, Portsmouth
df.tables[[46]] #Grimsby, Man City, West Brom (only 2 relegated)
dfxmas.tables[[84]] #Sunderland, Norwich, Birmingham
df.tables[[84]] #Man City, Swansea, Brighton
dfxmas.tables[[88]] # Newcastle, Charlton, Chelsea
df.tables[[88]] #Leicester, Man City, Villa
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment