更改列表中的 class 种类型

Change class types in a list

我有 运行 一系列“lmerModLmerTest”class 类型的模型,我已将其保存在列表中。我想将这些模型的 class 从“lmerModLmerTest”更改为“lmerTest”。

对于一个模型,我会这样改,效果很好:

class(model_1) <- "lmerMod"

然而,由于我有很多模型,因此我希望循环遍历我保存了所有这些模型的列表 (old_models)。

但是当我运行这个代码时:

mylist.df <- lapply(names(old_models),
                   function(x){
                   b <- as(old_models[[x]],"lmerMod")
                   b
                   })

生成的新列表 (mylist.df) 有 0 个元素。关于为什么会这样的任何想法? 非常感谢!

不要使用名字:

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"

reprex package (v2.0.1)

创建于 2022-02-09