The reason you get a list is because if x
is a matrix than cor(x)
will be a matrix as well, not a scalar. In this case it will be a 6x6 matrix. So the result is a list of 6x6 matrices, one for each factor level.
This is the natural way to represent the result, it seems to me. You can make it into a single data frame if you want, though I'm not sure what you want the rows and columns to represent exactly. Here is one option.
data<-matrix(rnorm(500),100,5)
colnames(data)<-letters[1:5]
factors<-sample(LETTERS[1:3],100,T)
cors<-by(data,factors,cor)
cors[[1]]
# a b c d e
# a 1.00000000 0.05389618 -0.16944040 0.25747174 0.21660217
# b 0.05389618 1.00000000 0.22735796 -0.06002965 -0.30115444
# c -0.16944040 0.22735796 1.00000000 -0.06625523 -0.01120225
# d 0.25747174 -0.06002965 -0.06625523 1.00000000 0.10402791
# e 0.21660217 -0.30115444 -0.01120225 0.10402791 1.00000000
corsMatrix<-do.call(rbind,lapply(cors,function(x)x[upper.tri(x)]))
names<-outer(colnames(data),colnames(data),paste,sep="X")
colnames(corsMatrix)<-names[upper.tri(names)]
corsMatrix
# aXb aXc bXc aXd bXd cXd
# A 0.05389618 -0.16944040 0.22735796 0.25747174 -0.06002965 -0.06625523
# B -0.34231682 -0.14225269 0.20881053 -0.14237661 0.25970138 0.27254840
# C 0.27199944 -0.01333377 0.06402734 0.02583126 -0.03336077 -0.02207024
# aXe bXe cXe dXe
# A 0.216602173 -0.3011544 -0.01120225 0.10402791
# B 0.347006942 -0.2207421 0.33123175 -0.05290809
# C 0.007748369 -0.1257357 0.23048709 0.16037247
I'm not sure if this is what you are looking for. Another option is to export each correlation matrix to its own csv file.