######################################################################################################
# Function to compute a linear fixed effects regression for panel data with weighting and robust SEs #
######################################################################################################

################################
# Last edited:                 #
# 26 July 2024 by Roni Lehrer  #
################################


weighted.fe.robust <- function(formula, data, group, time, weights) {
    demeaned <- copy(data)
    for (i in names(data)) {
        if (i%in%c(group, time, weights)==FALSE) {
            if (class(demeaned[, get(i)])!="character") {
                demeaned[, (i):=get(i)-mean(get(i)), get(group)]
                }
        }
    }
    if (any(grepl("-1", as.character(formula[[3]]), fixed = TRUE))==FALSE) {
     formula <- as.formula(paste0(formula[[2]], formula[[1]], formula[3], "-1"))
    }
    model <- lm(formula, data=demeaned, weights= get(weights))
    model$clustered.vcov <- vcovCL(model, cluster = as.formula(paste0("~", group)))
    return(model)
}
