3

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!

Rob
  • 26,989
  • 16
  • 82
  • 98
  • 3
    Please provide some reproducible data. See [here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for more info. – heds1 Jun 08 '19 at 22:31
  • 1
    Please don't make more work for other people by vandalizing your posts. By posting on Stack Overflow, you've granted a non-revocable right, under the [CC BY-SA 3.0 license](https://creativecommons.org/licenses/by-sa/3.0) for SO to distribute that content. By SO policy, any vandalism will be reverted. If you want to know more about deleting a post, please read more at [How does deleting work?](https://meta.stackexchange.com/q/5221) – iBug Jun 14 '19 at 00:24

1 Answers1

2

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))
demarsylvain
  • 2,103
  • 2
  • 14
  • 33