首页 > 解决方案 > 检查回归器的组合

问题描述

我有一个数据框,其中包含 6 个回归量 x1-x6 的 100 个值和自变量 y 的 100 个值。我的目标是在 2 个回归量上估计 y 的多元线性回归,并选择具有最高 R 平方的模型。我需要检查所有可能的 x 组合。例如,在 x1,x2 上估计模型 y;y 在 x1,x3 上;y 在 x2,x3 上等等。如何检查所有这些可能的组合,然后运行所有回归?可能我需要以某种方式使用 combn() 函数,但我不知道如何与回归估计一起执行此操作

标签: rdataframelinear-regression

解决方案


首先,我将创建一个可重现的数据集,因为您没有发布任何数据。

set.seed(1)    # make the results reproducible
n <- 100
X <- matrix(rnorm(6*n), ncol = 6)
y <- X %*% sample(6) + rnorm(n)

X <- as.data.frame(X)
names(X) <- paste0("x", 1:6)

data <- cbind(X, y)
head(data)

以下解决了连续*apply循环中的问题。它在以下步骤中进行。

  1. 只知道回归变量的全名以"x".
  2. 两两创建所有可能组合的矩阵。
  3. lapply在第一个循环中运行所有可能的回归。把公式放在一起paste然后强制到class "formula"
  4. 获取summary's,其中 R^2 的 th 值是用另一个 计算的lapply
  5. 就是这个。现在这两个列表具有标准子集运算符所需的所有信息,例如'[[',可以提取我们需要的任何内容。
    1. R^2 首先被提取,sapply因为它们将形成一个值向量
    2. 提取具有最大 R^2 的模型的系数和模型的摘要。

所以让我们去做吧。

regress <- grep("^x", names(data), value = TRUE)

regress_mat <- combn(regress, 2)

lm_list <- apply(regress_mat, 2, function(reg){
  fmla <- paste("y", paste(reg, collapse = "+"), sep = "~")
  fmla <- as.formula(fmla)
  lm(fmla, data)
})

smry_list <- lapply(lm_list, summary)
rsq <- sapply(smry_list, '[[', "r.squared")

coef(lm_list[[which.max(rsq)]])
#(Intercept)          x3          x4 
# -0.1400852   5.0556334   5.7352798

smry_list[[which.max(rsq)]]

#Call:
#  lm(formula = fmla, data = data)
#
#Residuals:
#     Min       1Q   Median       3Q      Max 
#-11.6529  -4.6230   0.1127   3.7821  11.9342 
#
#Coefficients:
#              Estimate Std. Error t value Pr(>|t|)    
#  (Intercept)  -0.1401     0.5763  -0.243    0.808    
#  x3            5.0556     0.5626   8.987 2.07e-14 ***
#  x4            5.7353     0.5867   9.775 4.11e-16 ***
#  ---
#  Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
#
#Residual standard error: 5.754 on 97 degrees of freedom
#Multiple R-squared:  0.6714,   Adjusted R-squared:  0.6646 
#F-statistic:  99.1 on 2 and 97 DF,  p-value: < 2.2e-16

推荐阅读