将相关矩阵转换为具有每个行列对记录的数据框 [英] Transform Correlation Matrix into dataframe with records for each row column pair
本文介绍了将相关矩阵转换为具有每个行列对记录的数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个很大的相关矩阵(1093 x 1093).我正在尝试将矩阵插入一个数据框,该数据框的每一行和每一列对都具有一列,因此它将是(1093)^ 2条记录.
I have a large matrix of correlations (1093 x 1093). I'm trying my matrix into a dataframe that has a column for every row and column pair, so it would (1093)^2 records.
这是我的矩阵的一个片段
Here's a snippet of my matrix
60516 45264 02117
60516 1.00000000 -0.370793012 -0.082897941
45264 -0.37079301 1.000000000 0.005145601
02117 -0.08289794 0.005145601 1.000000000
从这里开始的目标是拥有一个看起来像这样的数据框:
The goal from here would be to have a dataframe that looks like this:
row column correlation
60516 60516 1.000000000
60516 45264 -0.370793012
........等等.
........ and so on.
任何人都有提示吗?让我知道我是否可以澄清
Anyone have any tips? Let me know if I can clarify anything
谢谢, 本
推荐答案
对于矩阵m
,您可以执行以下操作:
For matrix m
, you could do:
data.frame(row=rownames(m)[row(m)], col=colnames(m)[col(m)], corr=c(m))
# row col corr
# 1 60516 60516 1.000000000
# 2 45264 60516 -0.370793010
# 3 02117 60516 -0.082897940
# 4 60516 45264 -0.370793012
# 5 45264 45264 1.000000000
# 6 02117 45264 0.005145601
# 7 60516 02117 -0.082897941
# 8 45264 02117 0.005145601
# 9 02117 02117 1.000000000
但是,如果您的矩阵是对称的,并且您对对角线不感兴趣,则可以将其简化为:
But if your matrix is symmetrical and if you are not interested in the diagonal, then you can simplify it to:
data.frame(row=rownames(m)[row(m)[upper.tri(m)]],
col=colnames(m)[col(m)[upper.tri(m)]],
corr=m[upper.tri(m)])
# row col corr
# 1 60516 45264 -0.370793012
# 2 60516 02117 -0.082897941
# 3 45264 02117 0.005145601
这篇关于将相关矩阵转换为具有每个行列对记录的数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文