将分组模型应用回数据 [英] Apply grouped model back onto data

查看:108
本文介绍了将分组模型应用回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我适合这样的模型

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>

我想我应该能够再次申请做,但我没有看到。或者,我可以按照

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使用的方法: / p>

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆