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

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...