只是为了扩展我的评论:plyr
具有组合输入和输出类型的功能集。因此,当您的函数返回不可转换的内容时,data.frame
您应该将list
其用作输出。所以不要使用ddply
use dlply
。
当你想在每个模型上做一些事情并将结果转换为data.frame
thenldply
是关键。
让我们使用创建一些模型dlply
list_of_models <- dlply(warpbreaks, .(tension), function(X) lm(breaks~wool, data=X))
str(list_of_models, 1)
# List of 3
# $ L:List of 13
# ..- attr(*, "class")= chr "lm"
# $ M:List of 13
# ..- attr(*, "class")= chr "lm"
# $ H:List of 13
# ..- attr(*, "class")= chr "lm"
# - attr(*, "split_type")= chr "data.frame"
# - attr(*, "split_labels")='data.frame': 3 obs. of 1 variable:
它给出list
了三个lm
模型。
使用ldply
你可以创建一个data.frame
,例如
每个模型的预测:
ldply(list_of_models, function(model) {
data.frame(fit=predict(model, warpbreaks))
})
# tension fit
# 1 L 44.5556
# 2 L 44.5556
# 3 L 44.5556
每个模型的统计信息:
ldply(list_of_models, function(model) {
c(
aic = extractAIC(model),
deviance = deviance(model),
logLik = logLik(model),
confint = confint(model),
coef = coef(model)
)
})
# tension aic1 aic2 deviance logLik confint1 confint2 confint3 confint4 coef.(Intercept) coef.woolB
# 1 L 2 98.3291 3397.78 -72.7054 34.2580 -30.89623 54.8531 -1.77044 44.5556 -16.33333
# 2 M 2 81.1948 1311.56 -64.1383 17.6022 -4.27003 30.3978 13.82559 24.0000 4.77778
# 3 H 2 76.9457 1035.78 -62.0137 18.8701 -13.81829 30.2411 2.26273 24.5556 -5.77778