Skip to content

Commit 31b1a8f

Browse files
authored
use weights when fitting LMM (#334) (#357)
(cherry picked from commit 3b96f3f)
1 parent dcd9242 commit 31b1a8f

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

src/linearmixedmodel.jl

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ function LinearMixedModel(f::FormulaTerm, tbl::Tables.ColumnTable;
4646
# TODO: perform missing_omit() after apply_schema() when improved
4747
# missing support is in a StatsModels release
4848
tbl, _ = StatsModels.missing_omit(tbl, f)
49-
sch = try
49+
sch = try
5050
schema(f, tbl, contrasts)
5151
catch e
5252
if isa(e, OutOfMemoryError)
@@ -82,6 +82,8 @@ function LinearMixedModel(f::FormulaTerm, tbl::Tables.ColumnTable;
8282
sort!(reterms, by=nranef, rev=true)
8383

8484
allterms = convert(Vector{Union{ReMat{T},FeMat{T}}}, vcat(reterms, feterms))
85+
sqrtwts = sqrt.(convert(Vector{T}, wts))
86+
reweight!.(allterms, Ref(sqrtwts))
8587
A, L = createAL(allterms)
8688
lbd = foldl(vcat, lowerbd(c) for c in reterms)
8789
θ = foldl(vcat, getθ(c) for c in reterms)

test/pls.jl

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -325,3 +325,24 @@ end
325325
@test rank(model) == 2
326326
@test length(coef(model)) == 3
327327
end
328+
329+
@testset "wts" begin
330+
# example from https://github.com/JuliaStats/MixedModels.jl/issues/194
331+
data = DataFrame(a = [1.55945122,0.004391538,0.005554163,-0.173029772,4.586284429,0.259493671,-0.091735715,5.546487603,0.457734831,-0.030169602],
332+
b = [0.24520519,0.080624178,0.228083467,0.2471453,0.398994279,0.037213859,0.102144973,0.241380251,0.206570975,0.15980803],
333+
c = categorical(["H","F","K","P","P","P","D","M","I","D"]),
334+
w1 = [20,40,35,12,29,25,65,105,30,75],
335+
w2 = [0.04587156,0.091743119,0.080275229,0.027522936,0.066513761,0.05733945,0.149082569,0.240825688,0.068807339,0.172018349])
336+
337+
#= no need to fit yet another model without weights, but here are the reference values from lme4
338+
m1 = fit(MixedModel, @formula(a ~ 1 + b + (1|c)), data)
339+
@test m1.θ ≈ [0.0]
340+
@test stderror(m1) ≈ [1.084912, 4.966336] atol = 1.e-4
341+
@test vcov(m1) ≈ [1.177035 -4.802598; -4.802598 24.664497] atol = 1.e-4
342+
=#
343+
344+
m2 = fit(MixedModel, @formula(a ~ 1 + b + (1|c)), data, wts = data.w1)
345+
@test m2.θ [0.295181729258352] atol = 1.e-4
346+
@test stderror(m2) [0.9640167, 3.6309696] atol = 1.e-4
347+
@test vcov(m2) [0.9293282 -2.557527; -2.5575267 13.183940] atol = 1.e-4
348+
end

0 commit comments

Comments
 (0)