Skip to content

Instantly share code, notes, and snippets.

@njudd
Last active April 22, 2025 08:15
Show Gist options
  • Select an option

  • Save njudd/dfd29ab40644bc5a0cf5e86eabf7474e to your computer and use it in GitHub Desktop.

Select an option

Save njudd/dfd29ab40644bc5a0cf5e86eabf7474e to your computer and use it in GitHub Desktop.
Residualize function
cols_to_res <- colnames(cog)[str_detect(colnames(cog), "_T")]
col_res <- function(df, response_var, predictor_string, model_func = lm){
# predictor_string <- paste(predictor_vars, collapse = " + ")
# Construct the full formula dynamically
formula_string <- paste(response_var, "~", predictor_string)
print(formula_string)
current_formula <- as.formula(formula_string)
m <- model_func(formula = current_formula, data = df, na.action = na.exclude)
return_df <- data.frame(as.numeric(resid(m)))
names(return_df) <- paste(response_var)
return(return_df)
}
cog.r <- cols_to_res %>%
map_dfc(~col_res(cog, ., "1 + site_id_l", model_func = lm))
cog.r <- cbind(cog[, !..res_col], cog.r)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment