I have a matrix on which I compute the correlations between my columns. I created a function which gives the result in the form of correlation matrix (because of the apply() function), but I would like to get a pairwise correlation dataframe directly. Is it possible to do that withouth any intermediate matrix : matrix -> pairwise correlation dataframe
cor_rho<-function(y) {
res <- foreach(i = seq_len(ncol(y)),
.combine = rbind,
.multicombine = TRUE,
.inorder = FALSE,
.packages = c('data.table', 'doParallel')) %dopar% {
apply(y, 2, function(x) 1 - ((var(y[,i] - x)) / (var(y[,i]) + var(x))))}
return(res)}
This is the same function, I just added some lines to get the data.frame I want
cor_rho<-function(y) {
res <- foreach(i = seq_len(ncol(y)),
.combine = rbind,
.multicombine = TRUE,
.inorder = FALSE,
.packages = c('data.table', 'doParallel')) %dopar% {
apply(y, 2, function(x) 1 - ((var(y[,i] - x)) / (var(y[,i]) + var(x))))}
colnames(res)=rownames(res)=colnames(y)
Df<-data.frame(var1=rownames(res)[row(res)[upper.tri(res)]],
var2=colnames(res)[col(res)[upper.tri(res)]],
corr=res[upper.tri(res)])
return(Df)}
which gives me something like this
var1 var2 value
var1 var3 value
var2 var3 value