如何对两个或多个因子自变量中的每个水平组合进行回归?
我想知道如何对两个或多个因子变量的水平组合执行多个独立线性回归。
假设我们的数据集有一个因连续变量,然后是两个因子自变量和一个连续自变量。
然后假设我们在 r 中的回归公式是这样的:
model <- lm(weight ~ city + diet + height)
或者,用伪代码编写我正在尝试这样做:
lm(weight ~ height) %>% group by city
lm(weight ~ height) %>% group by diet
lm(weight ~ height) %>% group by city & diet
我知道我们可以对每个城市和饮食逐一进行线性回归,但是您知道我们可以创建一个循环的方法,以便我们对数据集中的每个城市和饮食进行独立回归吗?
为了更好地说明这一点,我在这张图片中制作了这个假数据集,然后列出了我想要的三种类型的输出。但是,我不想手动一一执行,而是希望使用循环。
有谁知道如何在 r 中做到这一点?
回答
我们可以在列表中定义模型规范,然后lapply()在所需模型列表上使用。
代码
models <- list("m1" = c("weight", "height"),
"m2" = c("weight", "height", "city"),
"m3" = c("weight", "height", "diet"),
"m4" = c("weight", "height", "diet", "city"))
lapply(models, function(x){
lm(weight ~ ., data = df[, x])
})
# $m1
#
# Call:
# lm(formula = weight ~ ., data = df[, x])
#
# Coefficients:
# (Intercept) height
# -0.2970 0.1219
#
#
# $m2
#
# Call:
# lm(formula = weight ~ ., data = df[, x])
#
# Coefficients:
# (Intercept) height cityHouston
# -0.3705 0.1259 0.1205
#
#
# $m3
#
# Call:
# lm(formula = weight ~ ., data = df[, x])
#
# Coefficients:
# (Intercept) height dietVegan dietVegetarian
# -0.1905 0.1270 -0.1288 -0.1757
#
#
# $m4
#
# Call:
# lm(formula = weight ~ ., data = df[, x])
#
# Coefficients:
# (Intercept) height dietVegan dietVegetarian cityHouston
# -0.2615 0.1310 -0.1417 -0.1663 0.1197
数据
df <- data.frame("weight" = rnorm(100),
"height" = rexp(100),
"diet" = as.factor(sample(c("Vegan", "Vegetarian", "Meat"), replace = TRUE, 100)),
"city" = as.factor(sample(c("Houston", "Chicago"), replace = TRUE, 100)))