r - 组合对的相关性

标签 r matrix combinations correlation

我有 22 个变量,我想得到相关分数,不是作为相关矩阵,而是在数据框中,成对......

我的意思是...不是这样

    v1  v2  v3  v4
v1  1   x   x   x
v2  x   1   x   x
v3  x   x   1   x
v4  x   x   x   1

但像这样:
var1  var2 cor
v1    v2   x
v1    v3   x
v1    v4   x
v2    v3   x
v2    v4   x
v3    v4   x

我是 R 的新手,我一直在研究很多,最后我得到了一个代码,真诚地,根本没有效率......我的代码创建了一个巨大的数据框,其中包含 22 个变量的所有可能组合(其中是 4194304 组合......很多!!!)......然后代码只为前 211 行分配相关性,这是只有 2 个变量的组合......然后我排除了所有我不感兴趣的东西. 嗯......我得到了我需要的东西。但我确信这是一种非常愚蠢的方法,我想学习一种更好的方法......
有小费吗?

我的代码:
#Getting the variable names from the data frame
av_variables<-variable.names(data.1)

#Creating a huge data frame for all possible combinations
corr_combinations <- as.data.frame(matrix(1,0,length(av_variables)))
for (i in 1:length(av_variables)){
  corr_combinations.i <- t(combn(av_variables,i))
  corr_combinations.new <- as.data.frame(matrix(1,length(corr_combinations.i[,1]),length(av_variables)))
  corr_combinations.new[,1:i] <- corr_combinations.i
  corr_combinations <- rbind(corr_combinations,corr_combinations.new)

#How many combinations for 0:2 variables?
comb_par_var<-choose(20, k=0:2)
##211

#A new column to recieve the values
corr_combinations$cor <- 0


  #Getting the correlations and assigning to the empty column
 for (i in (length(av_variables)+1):(length(av_variables)+ sum(comb_par_var) +1)){
  print(i/length(corr_combinations[,1]))
  corr_combinations$cor[i] <- max(as.dist(abs(cor(data.1[,as.character(corr_combinations[i,which(corr_combinations[i,]!=0&corr_combinations[i,]!=1)])]))))
  # combinations$cor[i] <- max(as.dist(abs(cor(data.0[,as.character(combinations[i,combinations[i,]!=0&combinations[i,]!=1])]))))
  }

#Keeping only the rows with the combinations of 2 variables
corr_combinations[1:(length(av_variables)+ sum(comb_par_var) +2),21]
corr_combinations<-corr_combinations[1:212,]
corr_combinations<-corr_combinations[21:210,]

#Keeping only the columns var1, var2 and cor
corr_combinations<-corr_combinations[,c(1,2,21)]

#Ordering to keep only the pairs with correlation >0.95, 
#which was my purpose the whole time
corr_combinations <- corr_combinations[order(corr_combinations$cor),]
corr_combinations<-corr_combinations[corr_combinations$cor >0.95, ] 
}

最佳答案

您可以一次性计算完整的相关矩阵。然后你只需要 reshape 。一个例子,

cr <- cor(mtcars)
# This is to remove redundancy as upper correlation matrix == lower 
cr[upper.tri(cr, diag=TRUE)] <- NA
reshape2::melt(cr, na.rm=TRUE, value.name="cor")

关于r - 组合对的相关性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45825685/

相关文章:

R:在摘要中转换 do.call()-summary

javascript - 函数 createIdentityMatrix(a,b)

c++ - 如何使用带矩阵的透视图设置特定视点

algorithm - 我需要帮助来创建一个算法以从数字列表中返回可能的数字组列表

python-3.x - (Python)查找受分区大小限制限制的列表列表的所有可能分区

python - Rpy2、pyrserve 和 PypeR 如何比较?

r - 使用 mclapply 时,每个单核都比其非并行版本慢

PHP:如何获得一维数组的所有可能组合?

R Boxplot - 指定上下晶须?

python - numpy:矩阵乘法比向量的总和快吗?