user3670179
user3670179

Reputation: 55

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)

Upvotes: 0

Views: 269

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389175

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]>

Upvotes: 1

Related Questions