# Multiple fixed effects using FixedEffects.jl

**URL:** <https://discourse.julialang.org/t/multiple-fixed-effects-using-fixedeffects-jl/117113>\
**Category:** Statistics\
**Tags:** question, package, regression, linear-regression\
**Created:** [July 16, 2024, 7:58pm UTC](https://discourse.julialang.org/t/multiple-fixed-effects-using-fixedeffects-jl/117113 "2024-07-16T19:58:59Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![shilong-sun](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/shilong-sun/32/210695_2.png) [@shilong-sun](https://discourse.julialang.org/u/shilong-sun)\
**Post date:** [July 16, 2024, 7:58pm UTC](https://discourse.julialang.org/t/multiple-fixed-effects-using-fixedeffects-jl/117113/1 "2024-07-16T19:58:59Z")

</div>

Hi

I’m using `FixedEffects.jl` to residualize matrices with fixed effects. I might be missing something with the syntax, but I couldn’t get the same results using a simple regression approach. Below is the code from the readme file

```julia
using FixedEffects
# define fixed effects:
p1 = FixedEffect(repeat(1:5, inner = 2))
# combine fixed effects
p2 = FixedEffect(repeat(1:2, outer = 5), repeat(1:2, inner = 5))

x = rand(10)
x0 = copy(x)

# Regression approach
# fixed effect matrix
D = [p1.refs .== unique(p1.refs)' p2.refs .== unique(p2.refs)']
@time x1 = x0 - D*inv(D'*D)*D'*x0

#HDFE approach
@time solve_residuals!(x, [p1, p2])

# compare two methods
[x1 x]

```

---

<div class="post-metadata">

**Author:** ![nateybear](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nateybear/32/20645_2.png) [@nateybear](https://discourse.julialang.org/u/nateybear)\
**Post date:** [July 16, 2024, 10:41pm UTC](https://discourse.julialang.org/t/multiple-fixed-effects-using-fixedeffects-jl/117113/2 "2024-07-16T22:41:10Z")

</div>

It looks like your design matrix is wrong for the by-hand approach. It’s non-singular since you included all the indicator variables. The standard for the OLS dummy variable approach to fixed effects is to drop one level of the fixed effect. With the right D matrix, the answers are the same:

```julia
# ...same until here...
D = let dv_1 = p1.refs .== unique(p1.refs)[2:end]',
           dv_2 = p2.refs .== unique(p2.refs)[2:end]'
      [ones(Bool, 10) dv_1 dv_2]
    end

 @time x1 = let β = D \ x0
           x0 - D * β
       end

@time solve_residuals!(x, [p1, p2])

x ≈ x1

```

---

<div class="post-metadata">

**Author:** ![shilong-sun](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/shilong-sun/32/210695_2.png) [@shilong-sun](https://discourse.julialang.org/u/shilong-sun)\
**Post date:** [July 17, 2024, 2:16am UTC](https://discourse.julialang.org/t/multiple-fixed-effects-using-fixedeffects-jl/117113/3 "2024-07-17T02:16:30Z")

</div>

Thanks!
