Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using function lm() with group_by in R

I'm trying to create some lm() models for every level of the categorical variable, from one dataframe. I used function lm() with group_by, but it doesn't work, creating only one model. Of course, it is easy to create each datasets and use lm() for each of these, but I want to know other way, using group_by, apply, etc.

make_model <- function(data){
  lm(Sepal.Length~Sepal.Width,data)
}
models <- iris %>%
  group_by(Species) %>%
  make_model
predicted <- iris %>%
  group_by(Species) %>%
  mutate(prediction=predict(models,.))
like image 853
PenguinPartyH0 Avatar asked Oct 29 '25 21:10

PenguinPartyH0


1 Answers

A much more elegant solution than using nest() and all of its non-intuitive complexities, is to use group_modify, just part of the dplyr package:

library(dplyr)

iris %>%
  group_by(Species) %>%
  group_modify(~ broom::tidy(lm(Petal.Length ~ Sepal.Length, data = .x)))
#> # A tibble: 6 × 6
#> # Groups:   Species [3]
#>   Species    term         estimate std.error statistic  p.value
#>   <fct>      <chr>           <dbl>     <dbl>     <dbl>    <dbl>
#> 1 setosa     (Intercept)     0.803    0.344      2.34  2.38e- 2
#> 2 setosa     Sepal.Length    0.132    0.0685     1.92  6.07e- 2
#> 3 versicolor (Intercept)     0.185    0.514      0.360 7.20e- 1
#> 4 versicolor Sepal.Length    0.686    0.0863     7.95  2.59e-10
#> 5 virginica  (Intercept)     0.610    0.417      1.46  1.50e- 1
#> 6 virginica  Sepal.Length    0.750    0.0630    11.9   6.30e-16
like image 118
MS Berends Avatar answered Oct 31 '25 11:10

MS Berends



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!