I'm trying to make a list called "Models
" that contains a list of 10 models.
Here's the code I am using. (Typed into the interpreter)
models=list()
for (degree in 1:10){
myFormula=as.formula(paste0("nox ~ poly(dis, ",degree,")"))
myModel=lm(myFormula,data=Boston)
print(deviance(myModel))
models=append(models,myModel)
}
For some reason, the length of models after this is 120 instead of 10. I'm used to python, where the append statement would just add one object and they'd all be distinct.
I don't know why this isn't working that way or how to do it correctly.
CodePudding user response:
You can also use lapply
models = lapply(1:10, function(degree) {
myFormula=as.formula(paste0("nox ~ poly(dis, ",degree,")"))
lm(myFormula,data=Boston)
})
If you want the deviance of each model, you can do:
lapply(models, deviance)
Or equivalently
lapply(models, function(mod) deviance(mod))
You could also have returned both the model and its deviance (as a list) in the original loop like this; note that this returns a list of lists. The result, models
is 10 elements long (one for each degree
), and each element itself is a list (this one is a named list), with the first element being the model, and the second element being the variance
models = lapply(1:10, function(degree) {
myFormula=as.formula(paste0("nox ~ poly(dis, ",degree,")"))
mod = lm(myFormula,data=Boston)
list(model = mod, deviance=deviance(mod))
})
CodePudding user response:
We can add elements to list using c
,
models=list()
for (degree in 1:10){
myFormula=as.formula(paste0("nox ~ poly(dis, ",degree,")"))
myModel=lm(myFormula,data=Boston)
print(deviance(myModel))
models= c(models,list(myModel))
}