Skip to content

Instantly share code, notes, and snippets.

@dgrapov
Created January 6, 2024 08:56
Show Gist options
  • Save dgrapov/ee8e755025444f4afeee8b8a8c9a0756 to your computer and use it in GitHub Desktop.
Save dgrapov/ee8e755025444f4afeee8b8a8c9a0756 to your computer and use it in GitHub Desktop.
Example of linear model base covariate adjustment
#get linear model residuals
#' @import dplyr
#' @export
dave_lm_adjust<-function(data,formula,test_vars,adjust=TRUE,progress=TRUE){
if (progress == TRUE){ pb <- txtProgressBar(min = 0, max = ncol(data), style = 3)} else {pb<-NULL}
out <- lapply(1:length(test_vars), function(i) {
if (progress == TRUE) {
setTxtProgressBar(pb, i)
}
mod <-
tryCatch(
lm(as.formula(paste0(
"data[,'", test_vars[i], "']~", formula
)), data = data),
error = function(e) {
NULL
}
)
if (is.null(mod)) {
out<-NA
} else {
out<-residuals(mod)
}
if (progress == TRUE) {
close(pb)
}
out
}) %>%
do.call("cbind", .)
if(adjust){
min <- apply(out, 2, min, na.rm = T)
out <- lapply(1:ncol(out), function(i)
{
out[, i, drop = F] + abs(min[i])
}) %>%
do.call("cbind", .)
}
colnames(out)<-test_vars
return(out)
}
#------------------------------
#example of linear model based adjustment
#------------------------------
data(iris)
head(iris)
library(ggplot2)
ggplot(iris,aes(x=Sepal.Length,y=Petal.Width, color=Species)) +
geom_point() +
theme_minimal()
#variables to adjust
library(dplyr)
iris2<-dave_lm_adjust(iris, formula='Species',test_vars = colnames(iris)) %>%
data.frame()
#replace adjusted Species factor with the original
iris2$Species<-iris$Species
ggplot(iris2,aes(x=Sepal.Length,y=Petal.Width, color=Species)) +
geom_point() +
theme_minimal()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment