1

I want to do a polynomial regression for polynomials from 1 to 10:

library(ISLR)
attach(Auto)

myvec <- vector(length=10)
for (i in 1:length(myvec)){
    myvec[i]<-lm(mpg~poly(acceleration, i, raw=TRUE))
}

But summary(myvec[3]) is different from: summary(var1 <- lm(mpg~poly(acceleration, 3, raw=TRUE)))

How can I put output of functions into vectors with their original output type?

Teaman
  • 162
  • 9

1 Answers1

1

Do it like this and it should work:

mylist.names <- rep("A",10)
mylist <- vector("list", length(mylist.names))
names(mylist) <- mylist.names

for (i in 1:length(mylist)){
  mylist[[i]]<-lm(mpg~poly(acceleration, i, raw=TRUE))
}
Alex
  • 4,925
  • 2
  • 32
  • 48
  • So you create vector of lists, and there you put output of lm. Why do you index by [[i]]? I see that mylist[[i]] is the same as mylist[i] ,mylist[i] is i-th part of first vector. – Teaman Nov 14 '15 at 11:39
  • Try `class(mylist)`. It is actually not a vector. It is a list. What I did before I started the loop was just a little hack to create a list with 10 empty entries. You could also just do `mylist <- list()` and let the loop run from 1 to 10. Here is a question discussing the thing I think you are worrying about http://stackoverflow.com/questions/2050790/how-to-correctly-use-lists-in-r. – Alex Nov 14 '15 at 11:50
  • as (the other) @Alex notes, `vector(mode= "list", ...)` creates a list.... I believe you could use `mylist <- lapply(mylist, function(i) {lm(mpg~poly(acceleration, i, raw=TRUE))})` instead of the for loop (though I haven't tested it. – alexwhitworth Nov 14 '15 at 16:39