将分组模型重新应用到数据上 [英] Apply grouped model back onto data
本文介绍了将分组模型重新应用到数据上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我喜欢这样的模特
groupedTrainingSet = group_by(trainingSet, geo);
models = do(groupedTrainingSet, mod = lm(revenue ~ julian, data=.))
grouptedTestSet = group_by(testSet, geo);
// TODO: apply model back to test set
模型的样子
geo mod
1 APAC <S3:lm>
2 LATAM <S3:lm>
3 ME <S3:lm>
7 ROW <S3:lm>
4 WE <S3:lm>
5 NA <S3:lm>
我想我应该能够再次应用do",但我没有看到它......或者我可以做一些类似的事情
I think I should be able to just apply 'do' again but I'm not seeing it...Alternatively I can do something along the lines of
apply(trainingData, fitted =
predict(select(models, geo==geo)$mod, .));
但我不确定那里的语法.
But I'm not sure about the syntax there.
推荐答案
以下是获得类似答案的 dplyr
方法,遵循@Mike.Gahan 使用的方法:
Here is a dplyr
method of obtaining a similar answer, following the approach used by @Mike.Gahan :
library(dplyr)
iris.models <- iris %>%
group_by(Species) %>%
do(mod = lm(Sepal.Length ~ Sepal.Width, data = .))
iris %>%
tbl_df %>%
left_join(iris.models) %>%
rowwise %>%
mutate(Sepal.Length_pred = predict(mod,
newdata = list("Sepal.Width" = Sepal.Width)))
或者,如果您创建一个预测函数,您可以一步完成:
alternatively you can do it in one step if you create a predicting function:
m <- function(df) {
mod <- lm(Sepal.Length ~ Sepal.Width, data = df)
pred <- predict(mod,newdata = df["Sepal.Width"])
data.frame(df,pred)
}
iris %>%
group_by(Species) %>%
do(m(.))
这篇关于将分组模型重新应用到数据上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文