首页 > 解决方案 > 识别自变量之间的最高相关性值并排除与 r 中因变量的最低相关性

问题描述

我试图确定自变量之间的最高相关值(例如> = 0.8 | <= -0.8),然后排除与因变量具有最低相关值的变量以避免线性模型中的多重共线性。

首先,我想确定自变量之间的最高相关性,然后排除那些与第一行和第一列称为EC1的因变量相关性最低的变量

数据集,如果你想运行它

cor_26_EC<-rcorr(x=as.matrix(data_26_EM[c(4,8:length(data_26_EM))]),type="pearson")

cor_test<-(cor_26_EC$r)
> head(cor_test)
                     EC1         DEM       slope      aspect northernness   plan_curv   prof_curv convergence         twi
EC1           1.0000000 -0.68580505  0.36444948 -0.17735481   0.17735481 -0.14541592 -0.21159663 -0.10027208 -0.10220409
DEM          -0.6858051  1.00000000 -0.47325220  0.06090698  -0.06090698  0.28021257  0.34739247  0.24297883 -0.02919072
slope         0.3644495 -0.47325220  1.00000000 -0.02321129   0.02321129  0.04219001  0.01703231  0.03937512 -0.56400210
aspect       -0.1773548  0.06090698 -0.02321129  1.00000000  -1.00000000 -0.01574986 -0.01260762  0.04838931  0.02877949
northernness  0.1773548 -0.06090698  0.02321129 -1.00000000   1.00000000  0.01574986  0.01260762 -0.04838931 -0.02877949
plan_curv    -0.1454159  0.28021257  0.04219001 -0.01574986   0.01574986  1.00000000  0.59109001  0.73023077 -0.51818538

(it continues...)

标签: rmatrixsubsetcorrelation

解决方案


如果我理解正确,你想要一些类似的东西:

library("dplyr")
library("reshape2")

x <- read.delim("~/Documents/stack/EM_26.txt")
c <- cor(x)
## set diagonal to NA because we don't want autocorrelation
diag(c) <- NA
## reshape from matrix to long table
mdf <- melt(c)
## Choose max correlation for each variable
## You could also filter here by a threshold value, eg filter(abs(value) > 0.8)
max_cors <- mdf %>% group_by(Var1) %>% filter(value == max(value, na.rm = TRUE)) 
## For each max correlation, drop the one which has lower correlation with EC1
drop_variables <- apply(max_cors,
  1,
  function(row) {
    row[which.min(c(c["EC1", row[[1]]], c["EC1", row[[2]]]))]
  }
)
unique(drop_variables)
#> [1] "MS1"  "z"    "EC05"

推荐阅读