Reputation: 3011
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.
Upvotes: 0
Views: 251
Reputation: 7475
also maybe try
fit.list <- list()
for (i in 1:5) {
counts <- c(18,17,15,20,10,20,25,13,12)
outcome <- gl(3,1,9)
treatment <- gl(3,3)
print(d.AD <- data.frame(treatment, outcome, counts))
glm.D93 <- glm(counts ~ outcome + treatment, family=poisson())
fit.list[[i]] <-glm.D93
}
note the fit.list[[i]]
rather then fit.list[i]
as you have
Upvotes: 0
Reputation: 174853
Try
plot(fit.list[[15]])
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:
> mylist <- list(a = 1, b = "A", c = data.frame(X = 1:5, Y = 6:10))
> str(mylist)
List of 3
$ a: num 1
$ b: chr "A"
$ c:'data.frame': 5 obs. of 2 variables:
..$ X: int [1:5] 1 2 3 4 5
..$ Y: int [1:5] 6 7 8 9 10
> str(mylist["c"])
List of 1
$ c:'data.frame': 5 obs. of 2 variables:
..$ X: int [1:5] 1 2 3 4 5
..$ Y: int [1:5] 6 7 8 9 10
> str(mylist[["c"]])
'data.frame': 5 obs. of 2 variables:
$ X: int 1 2 3 4 5
$ Y: int 6 7 8 9 10
Notice the difference in the last two command outputs. str(mylist["c"])
says "List of 1
" whilst str(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.
Upvotes: 2