简体   繁体   中英

How to convert my stepwise regression in R into a FOR loop for many dependent variables

I currently have working code that uses 3rd order polynomial regression for many x's and 1 y. Then, it uses stepwise regression to find which selection of x's minimizes AIC for that y.

However, I would like to add more y's and use a for loop to find the minimum AIC for each y and then have it tell me which y had the minimum AIC.

My current working code:

SPdata <- read.csv(file.choose(), header=T,sep=",")

REG1 <- lm(Y1~poly(X1, 3)+poly(X2, 3)+poly(X3, 3), SPdata)

summary(REG1)

n <- length(resid(REG1))

REG2 = step(REG1, direction = "backward", k = log(n))

summary(REG2)

coefficients(REG2)

I also made this for loop which outputs the multiple regression for 3 y's, but I do not know how to include the stepwise regression part:

SPdata <- read.csv(file.choose(), header=T,sep=",")

varnames <- names(SPdata)[1:3]

REG3 <- lapply(varnames,

FUN=function(x) lm(formula(paste(x, "~poly(X1, 3)+poly(X2, 3)")), SPdata))

names (REG3) <- varnames

Thank you for your help!

You can create and name your function, and then use it in apply .

myRegression <- function(y){

  myReg1 <- lm(formula(paste(y, "~poly(X1, 3)+poly(X2, 3)")), SPdata))
  n      <- length(resid(myReg1))
  myReg2 <- step(MyReg1, direction = "backward", k = log(n))
  ...
}

myReg3 <- lapply(varnames, FUN = function(x) myRegression(x))

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