从R中的系数矩阵中过滤值

问题描述

我是R新手。 我从矩阵中选择数据有点问题。 我生成了如下的系数矩阵:

cor_mat <- cor(xxx,method = "spearman")

我想取值,即斯皮尔曼的相关系数大于或小于0.39或-0.39。

我的代码如下:

x1 <- c()
x2 <- c()
score <- c()
for (i in 1:length(rownames(cor_mat))) {
  for (j in 1:length(colnames(cor_mat))) {
    if(abs(cor_mat[i,j])>0.39 && rownames(cor_mat)[i] != colnames(cor_mat)[j]){
      x1 <- c(x1,paste0(rownames(cor_mat)[i]))
      x2 <- c(x2,colnames(cor_mat)[j])
      score <- c(score,paste0(cor_mat[i,j]))
    }
  }
}
high_cor_df <- data.frame(x1,x2,as.numeric(score))
attach(high_cor_df)

它有效,但是速度太慢。 有人可以帮我解决吗?

非常感谢您!

解决方法

使用tidyverse软件包的这种方法怎么样。

library(tidyverse)
set.seed(123)
xx <- data.frame(x = rnorm(100),y = runif(100),z = seq(100),w = seq(100)*runif(100),p = rev(seq(100))*runif(100))
cor_mat <- cor(xx,method = "spearman")
cor_mat %>% 
   as.data.frame() %>% 
   rownames_to_column(var = "var1") %>%
   pivot_longer(cols = -var1,names_to = "var2",values_to = "cor_coeff") %>%
   filter(var1 != var2 & abs(cor_coeff) >= 0.39)

 # A tibble: 4 x 3
  var1  var2  cor_coeff
  <chr> <chr>     <dbl>
1 z     w         0.641
2 z     p        -0.599
3 w     z         0.641
4 p     z        -0.599