Stat.Enthus
Stat.Enthus

Reputation: 335

Running an lm model for each df separately

I am trying to run a different model for each df and store it all in the same df after nesting.

Code example:

mt<- mtcars %>% group_by(cyl,am) %>% nest() %>% 
  mutate(formula = "Add separate model for each row in text like mpg~wt for one row, mpg~wt+hp for another etc.")

mt$formula[[1]] <- "mpg~wt"
mt$formula[[2]] <- "mpg~wt+drat"
mt$formula[[3]] <- "mpg~wt+qsec"
mt$formula[[4]] <- "mpg~wt+gear"
mt$formula[[5]] <- "mpg~wt"

mt<- mutate(model = ?)

Upvotes: 1

Views: 55

Answers (1)

akrun
akrun

Reputation: 887048

We can use map2 to loop over the list column 'data' and the corresponding elements of 'formula', apply the lm and assign it back to a new column 'model'

library(purrr)
mt$model <- vector('list', nrow(mt))
mt$model[1:5] <- map2(mt$data[1:5], mt$formula[1:5], ~ lm(.y, data = .x))
mt
# A tibble: 6 x 5
# Groups:   cyl, am [6]
#    cyl    am data              formula                                                                                  model
#  <dbl> <dbl> <list>            <chr>                                                                                    <lis>
#1     6     1 <tibble [3 × 9]>  mpg~wt                                                                                   <lm> 
#2     4     1 <tibble [8 × 9]>  mpg~wt+drat                                                                              <lm> 
#3     6     0 <tibble [4 × 9]>  mpg~wt+qsec                                                                              <lm> 
#4     8     0 <tibble [12 × 9]> mpg~wt+gear                                                                              <lm> 
#5     4     0 <tibble [3 × 9]>  mpg~wt                                                                                   <lm> 
#6     8     1 <tibble [2 × 9]>  Add separate model for each row in text like mpg~wt for one row, mpg~wt+hp for another … <NUL…

Upvotes: 4

Related Questions