使您的数据集更容易导入到 R:
dat <-
structure(list(A = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("a",
"b", "c"), class = "factor"), B = structure(c(1L, 2L, 3L, 4L,
1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L,
1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L
), .Label = c("a", "b", "c", "d"), class = "factor"), C = c(0.47,
0.88, 2.32, 3.26, 0.93, 1.86, 3.22, 0.92, 0.45, 0.92, 2.31, 3.24,
0.91, 1.84, 3.27, 0.86, 0.47, 0.9, 2.33, 3.19, 0.92, 1.84, 3.25,
0.93, 0.45, 0.92, 2.33, 3.08, 0.93, 1.86, 3.25, 0.93, 0.47, 0.9,
2.26, 3.09)), .Names = c("A", "B", "C"), class = "data.frame", row.names = c(NA,
-36L))
大部分 SAS 通过组处理映射到拆分-应用-组合方法(将数据分成几部分,对每个部分做一些事情,以某种方式将这些部分重新组合在一起)。在这种情况下,模型的结果是对象(列表),“组合”多个模型的自然方法是将它们放在列表中。
library("plyr")
models <- dlply(dat, .(B), function(DF) glm(C~A, data=DF))
models
现在是一个列表,其中的每个元素都是 的glm
子集上 a的结果dim
。
> models
$a
Call: glm(formula = C ~ A, data = DF)
Coefficients:
(Intercept) Ab Ac
6.167e-01 1.500e-01 6.799e-17
Degrees of Freedom: 8 Total (i.e. Null); 6 Residual
Null Deviance: 0.472
Residual Deviance: 0.427 AIC: 6.107
$b
Call: glm(formula = C ~ A, data = DF)
Coefficients:
(Intercept) Ab Ac
1.220000 0.306667 0.006667
Degrees of Freedom: 8 Total (i.e. Null); 6 Residual
Null Deviance: 1.99
Residual Deviance: 1.806 AIC: 19.09
$c
Call: glm(formula = C ~ A, data = DF)
Coefficients:
(Intercept) Ab Ac
2.616667 0.333333 -0.003333
Degrees of Freedom: 8 Total (i.e. Null); 6 Residual
Null Deviance: 1.958
Residual Deviance: 1.733 AIC: 18.72
$d
Call: glm(formula = C ~ A, data = DF)
Coefficients:
(Intercept) Ab Ac
2.4733 -0.8133 -0.1067
Degrees of Freedom: 8 Total (i.e. Null); 6 Residual
Null Deviance: 11.4
Residual Deviance: 10.23 AIC: 34.69
attr(,"split_type")
[1] "data.frame"
attr(,"split_labels")
B
1 a
2 b
3 c
4 d
一次从所有模型中提取信息遵循相同的范例:
> ldply(models, coefficients)
B (Intercept) Ab Ac
1 a 0.6166667 0.1500000 6.798700e-17
2 b 1.2200000 0.3066667 6.666667e-03
3 c 2.6166667 0.3333333 -3.333333e-03
4 d 2.4733333 -0.8133333 -1.066667e-01