简体   繁体   English

在R中存储和访问模型结果

[英]Storing and accessing model results in R

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. 但后来我想访问每个模型结果,例如summary(fit.list[4])plot(fit.list[15])但这似乎不起作用。

Try 尝试

plot(fit.list[[15]])

The single [ function extracts a list with the requested component(s), even if that list if of length 1. 单个[函数]提取具有所请求组件的列表,即使长度为1的列表也是如此。

The double [[ function extracts the single stated component and returns it but not in a list; double [[ function]提取单个声明的组件并将其返回但不在列表中; ie 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': ". str(mylist["c"])表示“ List of 1 ”,而str(mylist[["c"]])表示“ '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. 根据你的plot(fit.list[15])你要求R绘制一个列表对象,而不是列表中该元素所包含的模型。

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 请注意fit.list[[i]]而不是fit.list[i]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM