covs <- c("gender4", "educ", "race", "hispanic", "inputstate", "region", "urbancity", "employ", "student", "marstat",
"child18", "ownhome", "faminc_new", "religpew", "pew_bornagain", "pew_religimp", "pew_churatd", "pew_prayer",
"milstat_1", "milstat_3", "healthins_2", "sexuality", "immstat", "internethome",
"CC23_300_1", "CC23_300_2", "CC23_300_3", "CC23_300_4", "CC23_305_4", "CC23_305_6")
core <- c("gender4", "educ", "race", "urbancity", "marstat", "pew_religimp", "region", "ownhome", "child18",
"faminc_new", "religpew", "employ")
by_age <- c("gender4", "educ", "race", "urbancity", "pew_religimp", "region") # each gets its own age curve
ces_covs <- ces %>% select(all_of(covs)) %>%
mutate(across(everything(), ~ fct_na_value_to_level(fct_drop(as_factor(.x)), "missing")))
X_main_int <- sparse.model.matrix(reformulate(c(".", paste0("(", paste(core, collapse = " + "), ")^2"))), ces_covs)[, -1]
age_basis <- cbind(age = ces$age, tp_basis(ces$age, seq(22, 88, by = 2)))
D_by <- sparse.model.matrix(reformulate(by_age), ces_covs)[, -1]
X_age_by <- do.call(cbind, lapply(colnames(D_by), function(v) {
Matrix(age_basis * D_by[, v], sparse = TRUE, dimnames = list(NULL, paste0(colnames(age_basis), ":", v)))
}))
X_big <- cbind(Matrix(age_basis, sparse = TRUE), X_main_int, X_age_by)
X_big <- X_big[, colSums(X_big != 0) >= 50] # drop columns that are non-zero for fewer than 50 respondents
dim(X_big)