How to perform group-wise linear regression for a data frame in R?

The group−wise linear regression means creating regression model for group levels. For example, if we have a dependent variable y and the independent variable x also a grouping variable G that divides the combination of x and y into multiple groups then we can create a linear regression model for each of the group. In R, we can convert data frame to data.table object, this will help us to create the regression models easily.

Example

df2[,as.list(coef(lm(Salary~Ratings))),by=Class]

Output

Class (Intercept) Ratings
1: I 31894.13 194.9152
2: III 35270.10 663.4089
3: II 40405.42 -1087.9103
Updated on: 2026-03-11T23:22:53+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements