I want to perform model comparison according to several criteria using R.
My dataframe's name is df
head(df)
Y X1 X2 X3 X4
1 18 307 130 3504 12.0
2 15 350 165 3693 11.5
3 18 318 150 3436 11.0
4 16 304 150 3433 12.0
5 17 302 140 3449 10.5
6 15 429 198 4341 10.0
I want to compare all possible combinations with Y as the dependent variable. I'll give you what I've done so far to get the R.squared for all possible models. I would like your comments for better coding, especially on getting all those model formulas
# First get all possible combinations of the 4 inependent variables
comb_list <- lapply(1:4,function(i) combn(4,i))
# now create the formulas
comb_list_forms <- lapply(unlist(
sapply(1:length(comb_list), function(i)
sapply(1:dim(comb_list[[i]])[2], function(x) {nam <- names(df[1+comb_list[[i]][,x]])
formul <- "Y~"
sapply(1:length(nam), function(y) formul <<- paste(formul,nam[y],sep="+"))
formul <- sub("~+", "~", formul,fixed = T)
}))),as.formula)
# finally get r.squared
attach(df)
models.r.sq <- sapply(comb_list_forms, function(i) summary(lm(i))$r.squared)
Thank you