从 R 中的系数矩阵过滤值
filter values from a coefficient matrix in 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