load("CHESwork.RData")

ESSyears <- c(2002,
              2003,
              2004,
              2005,
              2006,
              2007,
              2008,
              2009,
              2010,
              2011,
              2012,
              2013,
              2014,
              2015,
              2016,
              2017,
              2018,
              2019,
              2020,
              2021,
              2022)

#' For each year and each party, find the year of the last election
#' that is: for each year and each party, find the largest CHESyear <= year

CHES_year <- subset(CHESwork,select=c(party_id,CHESyear))

CHES_ESS_year <- merge(data.frame(year=ESSyears),
                       CHES_year)

str(CHES_year)
str(CHES_ESS_year)

source("utils/complete-csets.R")

CHES_ESS_year <- Split(CHES_ESS_year,
                       by=~year+party_id)

get_latest_CHES <- function(data){
    year <- unique(data$year)
    CHESyear <- data$CHESyear
    if(any(CHESyear<=year)){
        latest <- max(CHESyear[CHESyear<=year])
        res <- subset(data,CHESyear==latest)
    }
    else res <- subset(data,FALSE)
    res
}

CHES_ESS <- lapply(CHES_ESS_year,
                   get_latest_CHES)

CHES_ESS <- do.call(rbind,CHES_ESS)

str(CHES_ESS)

save(CHES_ESS,
     file="CHES_ESS.RData")
