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,726
  • 2
  • 29
  • 44
  • 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 – Alex Nov 14 '15 at 11:50
  • as (the other) @Alex notes, `vector(mode= "list", ...)` creates a list.... I believe you could use `mylist – Alex W Nov 14 '15 at 16:39