简体   繁体   中英

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

I have a data set with 17 variables在此处输入图片说明

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)

在此处输入图片说明

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.

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))
    }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM