看起来您想要使用两个变量的所有组合的模型。这是使用内置的另一种方法mtcars
用于说明和使用的数据框mpg
作为结果变量。
我们得到两个变量的所有组合(不包括结果变量,mpg
在这种情况下)使用combn
. combn
返回一个列表,其中每个列表元素都是一个包含一对变量名称的向量。然后我们使用map
(来自purrr
包)为每对变量创建模型并将结果存储在列表中。
We use reformulate
来构建模型公式。.x
引用回变量名称的向量(每个元素vars
)。例如,如果你跑步,reformulate(paste(c("cyl", "disp"),collapse="*"), "mpg")
,你可以看到什么reformulate
是在做。
library(purrr)
# Get all combinations of two variables
vars = combn(names(mtcars)[-grep("mpg", names(mtcars))], 2, simplify=FALSE)
现在我们要对所有变量对运行回归模型并将结果存储在列表中:
# No interaction
models = map(vars, ~ glm(reformulate(.x, "mpg"), data=mtcars))
# Interaction only (no main effects)
models = map(vars, ~ glm(reformulate(paste(.x, collapse=":"), "mpg"), data=mtcars))
# Interaction and main effects
models = map(vars, ~ glm(reformulate(paste(.x, collapse="*"), "mpg"), data=mtcars))
使用该模型的公式命名每个列表元素:
names(models) = map(models, ~ .x[["terms"]])
使用以下命令创建模型公式paste
代替reformulate
你可以做(改变+
to :
or *
,取决于您想要包含的交互作用和主效应的组合):
models = map(vars, ~ glm(paste("mpg ~", paste(.x, collapse=" + ")), data=mtcars))
看看如何paste
这里正在使用,你可以运行:
paste("mpg ~", paste(c("cyl", "disp"), collapse=" * "))
当模型同时包含主效应和交互作用时,前两个模型如下所示:
models[1:2]
$`mpg ~ cyl * disp`
Call: glm(formula = reformulate(paste(.x, collapse = "*"), "mpg"),
data = mtcars)
Coefficients:
(Intercept) cyl disp cyl:disp
49.03721 -3.40524 -0.14553 0.01585
Degrees of Freedom: 31 Total (i.e. Null); 28 Residual
Null Deviance: 1126
Residual Deviance: 198.1 AIC: 159.1
$`mpg ~ cyl * hp`
Call: glm(formula = reformulate(paste(.x, collapse = "*"), "mpg"),
data = mtcars)
Coefficients:
(Intercept) cyl hp cyl:hp
50.75121 -4.11914 -0.17068 0.01974
Degrees of Freedom: 31 Total (i.e. Null); 28 Residual
Null Deviance: 1126
Residual Deviance: 247.6 AIC: 166.3
要评估模型输出,您可以使用以下函数broom
包裹。下面的代码返回数据帧,分别包含每个模型的系数和性能统计数据。
library(broom)
model_coefs = map_df(models, tidy, .id="Model")
model_performance = map_df(models, glance, .id="Model")
以下是具有主效应和交互作用的模型的结果:
head(model_coefs, 8)
Model term estimate std.error statistic p.value
1 mpg ~ cyl * disp (Intercept) 49.03721186 5.004636297 9.798357 1.506091e-10
2 mpg ~ cyl * disp cyl -3.40524372 0.840189015 -4.052950 3.645320e-04
3 mpg ~ cyl * disp disp -0.14552575 0.040002465 -3.637919 1.099280e-03
4 mpg ~ cyl * disp cyl:disp 0.01585388 0.004947824 3.204212 3.369023e-03
5 mpg ~ cyl * hp (Intercept) 50.75120716 6.511685614 7.793866 1.724224e-08
6 mpg ~ cyl * hp cyl -4.11913952 0.988229081 -4.168203 2.672495e-04
7 mpg ~ cyl * hp hp -0.17068010 0.069101555 -2.469989 1.987035e-02
8 mpg ~ cyl * hp cyl:hp 0.01973741 0.008810871 2.240120 3.320219e-02