I have run a series of "lmerModLmerTest" class-type models, which I have saved in a list. I would like to change the class of these models from "lmerModLmerTest" to "lmerTest".
For one model, I would change it like this, which works nicely:
class(model_1) <- "lmerMod"
However as I have many models I would ideally like to loop through the list in which I have saved all these models (old_models).
However when I run this code:
mylist.df <- lapply(names(old_models),
function(x){
b <- as(old_models[[x]],"lmerMod")
b
})
the resulting new list (mylist.df) has 0 elements. Any ideas as to why this is the case? Many thanks!
CodePudding user response:
Do not use names:
library(lmerTest)
#> Loading required package: lme4
#> Loading required package: Matrix
#>
#> Attaching package: 'lmerTest'
#> The following object is masked from 'package:lme4':
#>
#> lmer
#> The following object is masked from 'package:stats':
#>
#> step
library(lme4)
old_models <- list(
lmerTest::lmer(Sepal.Length ~ Sepal.Width (1|Species) , data = iris),
lmerTest::lmer(Sepal.Width ~ Sepal.Length (1|Species) , data = iris)
)
old_models
#> [[1]]
#> Linear mixed model fit by REML ['lmerModLmerTest']
#> Formula: Sepal.Length ~ Sepal.Width (1 | Species)
#> Data: iris
#> REML criterion at convergence: 194.6361
#> Random effects:
#> Groups Name Std.Dev.
#> Species (Intercept) 1.010
#> Residual 0.438
#> Number of obs: 150, groups: Species, 3
#> Fixed Effects:
#> (Intercept) Sepal.Width
#> 3.4062 0.7972
#>
#> [[2]]
#> Linear mixed model fit by REML ['lmerModLmerTest']
#> Formula: Sepal.Width ~ Sepal.Length (1 | Species)
#> Data: iris
#> REML criterion at convergence: 71.8035
#> Random effects:
#> Groups Name Std.Dev.
#> Species (Intercept) 0.5706
#> Residual 0.2890
#> Number of obs: 150, groups: Species, 3
#> Fixed Effects:
#> (Intercept) Sepal.Length
#> 1.0448 0.3444
sapply(old_models, class)
#> [1] "lmerModLmerTest" "lmerModLmerTest"
new_models <- lapply(old_models, function(x) as(x, "lmerMod"))
new_models
#> [[1]]
#> Linear mixed model fit by REML ['lmerMod']
#> Formula: Sepal.Length ~ Sepal.Width (1 | Species)
#> Data: iris
#> REML criterion at convergence: 194.6361
#> Random effects:
#> Groups Name Std.Dev.
#> Species (Intercept) 1.010
#> Residual 0.438
#> Number of obs: 150, groups: Species, 3
#> Fixed Effects:
#> (Intercept) Sepal.Width
#> 3.4062 0.7972
#>
#> [[2]]
#> Linear mixed model fit by REML ['lmerMod']
#> Formula: Sepal.Width ~ Sepal.Length (1 | Species)
#> Data: iris
#> REML criterion at convergence: 71.8035
#> Random effects:
#> Groups Name Std.Dev.
#> Species (Intercept) 0.5706
#> Residual 0.2890
#> Number of obs: 150, groups: Species, 3
#> Fixed Effects:
#> (Intercept) Sepal.Length
#> 1.0448 0.3444
sapply(new_models, class)
#> [1] "lmerMod" "lmerMod"
Created on 2022-02-09 by the reprex package (v2.0.1)