Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

r - Linear Regression fit (augment) on a different dataset

I'm simply trying to calculate the prediction (fitted values) on a different dataset the regression model was built on using dplyr and the augment function. However I keep getting errors. Even without using dplyr, the augment function seems to only accept the dataset the model was built on. Any solution to resolve that? Below is one of my attempt. Thank you.

data1 <- head(mtcars,20)

model <- mtcars %>%
  group_by(cyl) %>%
  do(fit = lm(wt ~ mpg, .),
     data = (.)) %>%
  augment(fit, data1)


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

1 Reply

0 votes
by (71.8m points)

Use augment in mutate and use map to pass one model at a time in augment.

library(broom)
library(dplyr)
library(purrr)

mtcars %>%
  group_by(cyl) %>%
  do(fit = lm(wt ~ mpg, .),
     data = (.)) %>%
  ungroup() %>%
  mutate(col   = map(fit, augment, newdata = data1))

Also since do has been superseded you can fit the model in summarise.

mtcars %>%
  group_by(cyl) %>%
  summarise(fit = list(lm(wt ~ mpg)), 
            data = list(cur_data())) %>%
  mutate(col   = map(fit, augment, newdata = data1))

#    cyl fit    data               col               
#  <dbl> <list> <list>             <list>            
#1     4 <lm>   <tibble [11 × 11]> <tibble [20 × 14]>
#2     6 <lm>   <tibble [7 × 11]>  <tibble [20 × 14]>
#3     8 <lm>   <tibble [14 × 11]> <tibble [20 × 14]>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...