How to create a linear regression model for each of the group

I want to do this code in Julia, is there any way to achieve it? Thank you for your help!

If I understand your screenshot correctly it’s something like this (slightly hacky way of accessing the group name, there’s probably a better way):

julia> using DataFrames, GLM

julia> df = DataFrame(G = rand('A':'D', 50), x1 = randn(50), y = randn(50));

julia> [(first(first(gdf).G), coef(lm(@formula(y ~ x1), gdf))) for gdf ∈ groupby(df, :G)]
4-element Vector{Tuple{Char, Vector{Float64}}}:
 ('D', [0.2590468147076215, 0.18017049456177228])
 ('B', [0.06914829093952116, 0.8148962459039837])
 ('C', [-0.20806955860375123, 0.15624480441068453])
 ('A', [-0.19031169433664966, 0.0535534286170727])

although note that this is the same as just interacting x1 and the group indicator (allowing a different slope and intercept per group):

ulia> lm(@formula(y ~ x1*G), df)
StatsModels.TableRegressionModel{LinearModel{GLM.LmResp{Vector{Float64}}, GLM.DensePredChol{Float64, LinearAlgebra.CholeskyPivoted{Float64, Matrix{Float64}}}}, Matrix{Float64}}

y ~ 1 + x1 + G + x1 & G

Coefficients:
──────────────────────────────────────────────────────────────────────────
                  Coef.  Std. Error      t  Pr(>|t|)  Lower 95%  Upper 95%
──────────────────────────────────────────────────────────────────────────
(Intercept)  -0.190312     0.328665  -0.58    0.5657  -0.853585   0.472961
x1            0.0535534    0.284165   0.19    0.8514  -0.519915   0.627022
G: B          0.25946      0.424046   0.61    0.5439  -0.5963     1.11522
G: C         -0.0177579    0.456611  -0.04    0.9692  -0.939235   0.90372
G: D          0.449359     0.429051   1.05    0.3009  -0.416501   1.31522
x1 & G: B     0.761343     0.48832    1.56    0.1265  -0.224127   1.74681
x1 & G: C     0.102691     0.401754   0.26    0.7995  -0.708082   0.913464
x1 & G: D     0.126617     0.362336   0.35    0.7285  -0.604606   0.85784
──────────────────────────────────────────────────────────────────────────

(here A is the base category, so intercept and x1 coefficient are the same as for A above, and e.g. B’s intercept is given by -0.19+0.259 = 0.069 and slope by 0.05 + 0.76 = 0.81)

1 Like

For the future, don’t screenshot text, paste it. Easier to read, copy-and-run, search and quote. If that seems like extra work for you, consider that you are expecting people to help you, and putting in the extra effort increases the chance someone will.

1 Like

Thank you sooooo much!!! :smiley:
really helps me a lot
have a great day!

1 Like

got it, thanks man :grinning: