Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

r - Apply grouped model back onto data

I fit models like so

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

Where models looks like

 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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(.))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...