How to perform group regression in R language

Many data analysis scenarios involve the problem of performing regression analysis within each group after grouping the data. In python, this function can be realized by applying groupby().apply() to a self-built regression function within the group. For the R language, there is a more convenient way to implement grouped regression.

Take the mtcars dataset as an example.

library(tidyverse)
library(broom)
# library(stargazer)

regr <- mtcars |> 
  group_by(am) |> 
  do(tidy(lm(mpg ~ wt, .)))

regr

In the above example, the mtcars data is grouped by am, and within each group, wt is used to perform regression on mpg.

The broom package is an integral part of tidymodels. Its function is to convert statistical type objects into tibble objects, so that it can be easily applied to the tidyverse process.

The tidy function converts an object into a tibble, and the do() function is used to pass parameters, namely group_by(am).

This article is published by mdnice multi-platform

Guess you like

Origin blog.csdn.net/amandus/article/details/130575911