Search code examples
rlinear-regression

How to make a for loop to find interactions between several variables in R?


I have a data set with 17 variables enter image description here

the data is available at this link http://www.uwyo.edu/crawford/stat3050/final%20project/maxwellchandler.txt

I want to find significant interactions between the variables.

For example

    fitcivilian<-lm(Civilian~Stock+Terrorism+log(Firepower)+Payload+Bombs*Temperature+FirstAid+Spies+Personnel+IG88, data=data)

enter image description here

where Bombs*Temperature is significant

What I want to do is test EVERY varaible against EVERY OTHER variable,

Like doing

Bombs*Temperature

Bombs*Napalm

IG88* Weapons

Missles*Firepower

etc. Till every combination of two is exhuasted

That way, I could find out if there are significant interactions between every variable.

I know how to do it manually, creating a linear model and then taking a summary of that model but I want to be able to create a loop that tests every variable because it would be a lot of entries to test everything.


Solution

  • I had done something similar. You will need to modify the loop for your need. Let me know if you need help with that.

        vars=colnames(mydata)[-1] 
        for (i in vars)  {
        for (j in vars) {
        if (i != j) {
        factor= paste(i,j,sep='*')}
        lm.fit <- lm(paste("Sales ~", factor), data=mydata)
        print(summary(lm.fit))
        }}