创建新数据集,删除具有高通胀因子的变量

时间:2012-03-28 09:49:00

标签: r loops

我有一个环境变量数据集,我想用于GLMM。我正在使用corvif包中的AED函数(http://www.highstat.com/Book2/AED_1.0.zip)来识别和删除具有高通胀因子的变量。

不是手动从我的数据集中删除一个变量,而是使用GVIF值&gt; 3(首先删除最高值),我想知道如何编写一个循环来自动完成此任务,结果是一个只有剩余变量的新数据集(即那些GVIF values < 3)。

有关如何为新R用户解决此问题的任何建议吗?

以下是我的示例数据:

WW_Covs <- structure(list(Latitude = c(62.4419, 67.833333, 65.95, 63.72935,
60.966667, 60.266667, 55.660455, 62.216667, 61.3, 61.4, 62.084139,
55.662566, 64.48508, 63.208354, 62.87591, 62.70856, 62.64009,
63.79488, 59.55, 62.84206), BIO_02 = c(87, 82, 75, 70, 77, 70,
59, 84, 84, 79, 85, 60, 91, 87, 74, 74, 76, 70, 76, 74), BIO_03 = c(26,
23, 25, 26, 25, 24, 25, 25, 26, 25, 26, 26, 24, 25, 24, 25, 25,
25, 26, 24), BIO_04 = c(8443, 9219, 7594, 6939, 7928, 7593, 6160,
8317, 8167, 7972, 8323, 6170, 9489, 8578, 7814, 7680, 7904, 7149,
7445, 7803), BIO_05 = c(201, 169, 151, 166, 194, 210, 202, 205,
204, 186, 205, 200, 200, 195, 170, 154, 180, 166, 219, 170),
BIO_06 = c(-131, -183, -144, -102, -107, -75, -26, -119,
-113, -120, -120, -28, -169, -143, -131, -142, -124, -111,
-72, -129), BIO_08 = c(128, 109, 85, 78, 122, 145, 153, 134,
130, 126, 132, 152, 120, 119, 115, 98, 124, 104, 147, 115
), BIO_09 = c(-31, -81, -16, 13, -60, -6, 25, -25, -25, -70,
-25, 23, -56, -39, -47, -60, -39, 8, 0, -46), BIO_12 = c(667,
481, 760, 970, 645, 557, 645, 666, 652, 674, 670, 670, 568,
598, 650, 734, 620, 868, 571, 658), BIO_13 = c(78, 77, 96,
109, 85, 70, 67, 77, 84, 93, 78, 68, 72, 78, 93, 99, 90,
96, 72, 93), BIO_15 = c(23, 40, 25, 21, 36, 30, 21, 24, 28,
34, 24, 22, 28, 29, 34, 32, 36, 22, 30, 34), BIO_19 = c(147,
85, 180, 236, 108, 119, 154, 149, 135, 118, 148, 162, 117,
119, 120, 141, 111, 204, 111, 122)), .Names = c("Latitude",
"BIO_02", "BIO_03", "BIO_04", "BIO_05", "BIO_06", "BIO_08", "BIO_09",
"BIO_12", "BIO_13", "BIO_15", "BIO_19"), row.names = c(1:20), class = "data.frame")

示例代码:

library(AED)
WW_Final <- corvif(WW_Covs)
test <- corvif(WW_Covs])
test[order(-test$GVIF), ]
if(test$GVIF[1,] > 3, # this is where I get stuck...

1 个答案:

答案 0 :(得分:2)

这是一个执行此操作的算法。我使用内置数据集longley进行说明,并且还在包vif中使用函数car,而不是使用包AED

它不漂亮,应该包含在一个函数中,但我把它留作感兴趣的读者的练习。

代码:

library(car)

dat <- longley

cutoff <- 2
flag <- TRUE
while(flag){
  fit <- lm(Employed ~ ., data=dat)
  vfit <- vif(fit)
  if(max(vfit) > cutoff){
    dat <- dat[, -which.max(vfit)]
  } else {
    flag <- FALSE
  }
}

print(fit)
print(vfit)

输出:

Call:
lm(formula = Employed ~ ., data = dat)

Coefficients:
 (Intercept)    Unemployed  Armed.Forces  
    50.66281       0.02265       0.02847  

  Unemployed Armed.Forces 
    1.032501     1.032501