r - 识别自变量之间的最高相关性值并排除与 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...)
解决方案
如果我理解正确,你想要一些类似的东西:
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"
推荐阅读
- r - 如何将 `I()` 与 `paste0` 一起使用?
- flutter - 没有延迟调用 Bloc 侦听器
- wpf - 没有视图模型的 WPF 用户控件
- php - php json_encode():“格式错误的 UTF-8 字符”,尽管没有异常字符
- javascript - 有没有办法按标签解码/编码,但在 protobuf.js 中没有任何 .proto 文件或 json 文件?
- flutter - 在颤动中选择了多个行按钮
- unit-testing - 使用 kafka 流绑定器测试 Spring 云流:使用 TopologyTestDriver 我收到“该类不在受信任的包中”的错误
- typescript - 在 Vue 类组件装饰器中访问 getter
- r - 使用 purrr 根据条件从嵌套数据框中提取值
- javascript - 如何从html中获取标签的选定值?