singmann / afex

Analysis of Factorial EXperiments (R package)
120 stars 32 forks source link

Is it possible to coerce a "mixed" object into a "merModLmerTest" object? #43

Closed krisanathema closed 6 years ago

krisanathema commented 6 years ago

In order to compute R2 for generalized linear mixed-effects models, I use to follow the procedure described in Nakagawa & Schielzeth (2013). This procedure requires to access the fixef() and getME() functions, which do not work with "mixed" objects, as shows the following error message: Error in UseMethod("fixef") : no applicable method for 'fixef' applied to an object of class "mixed"

Is there any possibility to coerce a "mixed" object into a "merModLmerTest" object, or an equivalent object supported by fixef()?

Nakagawa & Schielzeth_2013_MEE_General and simple method for obtaining R2 from GLMMs.pdf

singmann commented 6 years ago

The mixed objects contains the merModLmerTest object in the full_model slot. This can be used with the functions you are interested in. For example:

library("afex")
data("Machines", package = "MEMSS") 

# simple model with random-slopes for repeated-measures factor
m1 <- mixed(score ~ Machine + (Machine|Worker), data=Machines)
str(m1, 1)
# List of 5
#  $ anova_table      :Classes ‘anova’ and 'data.frame':    1 obs. of  4 variables:
#   ..- attr(*, "heading")= chr [1:3] "Mixed Model Anova Table (Type 3 tests, KR-method)\n" "Model: score ~ Machine + (Machine | Worker)" "Data: Machines"
#   ..- attr(*, "sig_symbols")= chr [1:4] " +" " *" " **" " ***"
#  $ full_model       :Formal class 'merModLmerTest' [package "lmerTest"] with 13 slots
#  $ restricted_models: NULL
#  $ tests            : NULL
#  $ data             :'data.frame':    54 obs. of  3 variables:
#  - attr(*, "class")= chr "mixed"
#  - attr(*, "type")= num 3
#  - attr(*, "method")= chr "KR"

fixef(m1$full_model)
# (Intercept)    Machine1    Machine2 
#  59.6500000  -7.2944444   0.6722222 

getME(m1$full_model, name = "X")
#    (Intercept) Machine1 Machine2
# 1            1        1        0
# 2            1        1        0
# [...]
# 54           1       -1       -1
# attr(,"assign")
# [1] 0 1 1
# attr(,"contrasts")
# attr(,"contrasts")$Machine
# [1] "contr.sum"
# 
# attr(,"msgScaleX")
# character(0)

Let me know if this does not work for you.

krisanathema commented 6 years ago

Thanks a lot Henrik!

It works perfectly for me. I did not realize that merModLmerTest objects were already included in mixed objects.