I have some code that runs a model in a loop. Each iteration of the loop runs a slightly different model and the results are stored in a variable . What is a good way to store these objects so I can access them after the loop terminates ? I thought about something like this:
fit.list <- list(n)
for (i in 1:n) {
fit <- glm(......)
fit.list[i] <- fit
}
But then I want to access each model results, for example summary(fit.list[4]) or plot(fit.list[15]) but that doesn’t seem to work.
Try
The single
[function extracts a list with the requested component(s), even if that list if of length 1.The double
[[function extracts the single stated component and returns it but not in a list; i.e. you get the component itself not a list containing that component.Here is an illustration:
Notice the difference in the last two command outputs.
str(mylist["c"])says “List of 1” whilststr(mylist[["c"]])says “'data.frame':“.With your
plot(fit.list[15])you were asking R to plot a list object not the model contained in that element of the list.