# R-code for generating all combinations of interactions
# Adam Wagner October 2020
# install.packages("stringr")

library(stringr)
library(foreign)

#x <- read.spss("E:\\DEMO REGRESSION DATA\\crime data in usa.sav")
x <- read.spss("U:\\My Documents\\crime data in usa.sav")
x1 <- data.frame(x)
x4 <- na.omit(x1)
attach(x4)
education <- educatio

hasInt <- factor(c(0,1))
hasIntVars <- interaction(hasInt, hasInt) # Extend with the number of interactions interested in
# interaction() produces all the different combinations of the interactions
intGrpCombs <- levels(hasIntVars)
# e.g. "0.0" corresponds to the model with no interactions etc

#intGrpCombs
rm(hasInt)
hasInt <- factor(c("_","Y"))
hasIntVarsYN <- interaction(hasInt, hasInt)
intGrpCombsYN <- levels(hasIntVarsYN)

intTerms <- c("location:age", "location:education") # If more interactions to be included, add here

# Produce different strings with which to extend the base model
additionalTerms <- sapply(intGrpCombs,
                      function(x){
                        paste((intTerms)[c(F,T)[as.numeric(str_split(x, "\\.")[[1]])+1]],
                              collapse="+")})
additionalTerms[1] <- "" # Have the first model with no interaction
additionalTerms

# Main effects only model
baseModel <- lm(crime~age+education+location, data=)


# Next code creates a list of models, with every combination with and without interactions etc
allMods <- lapply(additionalTerms, 
                  function(x){
                    if(x=="")baseModel # No interactions
                    else update(baseModel, as.formula(paste(".~.", x, sep="+")))})
# The last line of code extends the baseModel using the update() with the elements of additionalTerms
# Ideally, the elements of allMods should be named to make tracking easier

allMods

# Then to find the lowest AIC etc
# in our example the model with the lowest AIC is the baseline model, 0.0, baseModel above
which.min(sapply(allMods, AIC))

