【问题标题】:How Do I Generate All Possible Combinations of the Variables In A Model In R?如何在 R 模型中生成变量的所有可能组合?
【发布时间】:2022-11-19 21:05:51
【问题描述】:

假设我有一个包含多个变量的表,a - h,其中 h 是目标/y/预测变量:

a <- rnorm(10,5,1)
b <- rnorm(10,5,1)
c <- rnorm(10,5,1)
d <- rnorm(10,5,1)
e <- rnorm(10,5,1)
f <- rnorm(10,5,1)
g <- rnorm(10,5,1)
h <- rnorm(10,5,1)

df = data.frame(a,b,c,d,e,f,g,h)

我想运行 AIC 以确定预测 h 的最佳模型。为此,我需要运行df[1:7] 的每一个组合。所以我需要以下 AIC:

lm(fomula= h ~ a+b+c+d+e+f+g)
lm(fomula= h ~ a+b+c+d+e+f)
lm(fomula= h ~ a+b+c+d+e)

以及变量的所有其他配置。有什么办法可以做到这一点吗?

要获得我尝试过的变量的所有可能公式:

library(combinat)
combn(colnames(df[,1:7]))

但是,我只得到:

[1] "a" "b" "c" "d" "e" "f" "g"

作为上面代码的输出,这与我最终想要的相去甚远。

【问题讨论】:

  • 从 MASS 包中查看stepAIC
  • 更好的是,使用 leaps 包在没有逐步约束的情况下获得最佳子集回归。 (或glmultibestglm

标签: r combinations permutation


【解决方案1】:

使用 step 函数。这应该给你最好的模型:

step(lm(h~., df),direction = 'both', trace = 0)

Call:
lm(formula = h ~ b + e + f, data = df)

Coefficients:
(Intercept)            b            e            f  
     4.3494      -0.8705      -0.3266       1.2877  

该型号最低AIC。您可以更改trace = 1,以查看运行的中间模型

【讨论】:

  • “最佳模型”——通过优化各个步骤从完整模型中可达到的最低 AIC 模型。通常,但现在总是与这些预测变量的所有可能组合中 AIC 最低的模型相同。
  • @GregorThomas 在这种情况下,给出的模型是这些预测变量所有可能组合中 AIC 最低的模型
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多