从lmer模型中提取L2变量的名称

时间:2020-03-18 21:52:14

标签: r lme4

我正在尝试为另一个函数编写包装函数。原始函数r2MLM(找到的here)为多层模型计算R平方值。但是,它需要直接输入估计值-固定效果,随机效果,tau矩阵等的估计值,这使它难以使用。

我想创建一个包装函数,只需向其输入模型名称,然后包装器将提取所有这些估计并将其提供给r2MLM。通过提供L1和L2变量的函数列表,然后从那里提取输出,我在此方面取得了良好的进展,但是我希望用户能够只输入他们的型号名称。有谁知道如何从lmer对象中提取L1和L2变量的名称?

我使用getME()尝试了多种解决方法,但是我只能设法消除固定和随机效应。我得到的最接近的是model.frame(model),它返回模型公式中使用的变量,并且我想您可以一遍又一遍地筛选具有相同值的变量,并将其称为L2变量?但这似乎非常混乱且容易出错,并且理论上您可以拥有一个L1变量,该变量在一个群集中一次又一次地重复。

下面是一些示例代码,显示了当前需要什么输入以及我想从哪里获得。为了避免混乱,我暂时省略了r2MLMr2MLM_wrapper_v1的功能代码,因为我认为没有必要理解这个问题,但是如果人们能找到它,我可以提供它有帮助。

# 1 Dependencies ----------------------------------------------------------

library(tidyverse)
library(lme4)
library(lmerTest)

# 2 Sample data -----------------------------------------------------------

df <- tribble(
  ~school, ~math, ~ses, ~public,
  #--------#-----#-----#-------
  1, 8, 3, 0,
  1, 7, 2, 0,
  1, 6, 4, 0,
  1, 8, 5, 0,
  1, 6, 2, 0,
  2, 9, 5, 1,
  2, 10, 3, 1,
  2, 4, 4, 1,
  2, 5, 4, 1,
  2, 9, 2, 1,
  3, 7, 3, 0, 
  3, 8, 2, 0,
  3, 9, 4, 0,
  3, 10, 2, 0,
  3, 8, 1, 0
)

# school = school ID
# math = math score, out of 10
# ses = socioeconomic status, out of 5
# public = public school (0 = private, 1 = public)

# 3 Run model with ses at L1, public at L2 --------------------------------

model <- lmer(math ~ 1 + ses + public + (1|school), data = df, REML = TRUE)
summary(model)

as.matrix(Matrix::bdiag(VarCorr(model))) # Print Tau matrix

# 4 Input to r2MLM to generate R-squared measures -------------------------

# this is the input required by the original function
# r2MLM(as.data.frame(df), within_covs = c(3), between_covs = c(4), random_covs = NULL, gamma_w = c(-0.2397), gamma_b = c(8.3712, -0.1082), Tau = matrix(c(0.09583922), 1, 1), sigma2 = 3.46968, has_intercept = TRUE, clustermeancentered = FALSE)

# r2MLM_wrapper_v1(model, "ses", "public", NULL, TRUE, df) # this is how far I've gotten in streamlining the input

# r2MLM_wrapper_final(model) # this is where I would like to get

0 个答案:

没有答案