从 lme4 模型中获取预测变量的 class

Getting the class of the predictors from an lme4 model

拟合 lme4 模型后,我想知道我们如何从 terms(fit)[[3]] 获得预测变量的 class?

这是一个简单的示例,但我很欣赏 lme4 中任何其他模型的功能性答案。

注意:所有内容都必须从模型中提取。

library(lme4)

h <- read.csv('https://raw.githubusercontent.com/hkil/m/master/h.csv')
h$year <- as.factor(h$year)
m <- lmer(scale~ year*group + (1|stid), data = h)

terms(m)[[3]]  ## What are the `class`es of the variables in here (e.g., `integer`, `factor` etc.)

可能不够稳健,但是:

  1. 从术语对象中提取变量名称
av <- all.vars(terms(m)[[3]])   ## c("year","group")
  1. 在作为 data=:
  2. 提供的数据框中查找它们
setNames(lapply(av, function(x) class(h[[x]])), av)
$year
[1] "factor"

$group
[1] "character"

如果您想从模型中获取所有内容,这通常会 更难 ,因为不一定存储原始变量。在您给出的示例中:

 setNames(lapply(av, function(x) class(model.frame(m)[[x]])), av)
$year
[1] "factor"

$group
[1] "factor"

您会注意到 group 已转换为因数。您可以打破这一点,例如,通过在模型中使用 log(x) 这样的术语 ...