Skip to content

Commit 48fd72d

Browse files
authored
Merge pull request #84 from Shotgunosine/fixef_labels
fix fixed effects indices
2 parents a4d4efc + 34d1ca2 commit 48fd72d

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

pymer4/models/Lmer.py

+10-1
Original file line numberDiff line numberDiff line change
@@ -748,13 +748,22 @@ def fit(
748748
# Cluster (e.g subject) level coefficients
749749
rstring = """
750750
function(model){
751+
getIndex <- function(df){
752+
orignames <- names(df)
753+
df <- transform(df, index=row.names(df))
754+
names(df) <- append(orignames, c("index"))
755+
df
756+
}
751757
out <- coef(model)
758+
out <- lapply(out, getIndex)
752759
out
753760
}
754761
"""
755762
fixef_func = robjects.r(rstring)
756763
fixefs = fixef_func(self.model_obj)
757-
fixefs = [pd.DataFrame(f) for f in fixefs]
764+
fixefs = [
765+
pd.DataFrame(e, index=e.index).drop(columns=["index"]) for e in fixefs
766+
]
758767
if len(fixefs) > 1:
759768
if self.coefs is not None:
760769
f_corrected_order = []

pymer4/tests/test_models.py

+20
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,8 @@ def test_gaussian_lmm():
105105
assert np.allclose(model.coefs["Estimate"], estimates, atol=0.001)
106106

107107
assert isinstance(model.fixef, list)
108+
assert (model.fixef[0].index.astype(int) == df.Group.unique()).all()
109+
assert (model.fixef[1].index.astype(float) == df.IV3.unique()).all()
108110
assert model.fixef[0].shape == (47, 3)
109111
assert model.fixef[1].shape == (3, 3)
110112

@@ -133,6 +135,24 @@ def test_gaussian_lmm():
133135
# Smoketest for old_optimizer
134136
model.fit(summarize=False, old_optimizer=True)
135137

138+
# test fixef code for 1 fixed effect
139+
model = Lmer("DV ~ IV3 + IV2 + (IV2|Group)", data=df)
140+
model.fit(summarize=False, control=opt_opts)
141+
142+
assert (model.fixef.index.astype(int) == df.Group.unique()).all()
143+
assert model.fixef.shape == (47, 3)
144+
assert np.allclose(model.coefs.loc[:, "Estimate"], model.fixef.mean(), atol=0.01)
145+
146+
# test fixef code for 0 fixed effects
147+
model = Lmer("DV ~ (IV2|Group) + (1|IV3)", data=df)
148+
model.fit(summarize=False, control=opt_opts)
149+
150+
assert isinstance(model.fixef, list)
151+
assert (model.fixef[0].index.astype(int) == df.Group.unique()).all()
152+
assert (model.fixef[1].index.astype(float) == df.IV3.unique()).all()
153+
assert model.fixef[0].shape == (47, 2)
154+
assert model.fixef[1].shape == (3, 2)
155+
136156

137157
def test_contrasts():
138158
df = sns.load_dataset("gammas").rename(columns={"BOLD signal": "bold"})

0 commit comments

Comments
 (0)