数据帧变成对称矩阵,同时保留所有行和列 [英] Data frame into a symmetric matrix while keeping all row and column
本文介绍了数据帧变成对称矩阵,同时保留所有行和列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
R DataFrame转换为正方形(对称)矩阵的问题是关于转换给出以下示例,将数据帧转换为对称矩阵:
The question R DataFrame into square (symmetric) matrix is about transforming a data frame into a symmetric matrix given the following example:
# data
x <- structure(c(1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0),
.Dim = c(3L,5L),
.Dimnames = list(c("X", "Y", "Z"), c("A", "B", "C", "D", "E")))
x
# A B C D E
#X 1 1 0 0 0
#Y 1 1 0 0 0
#Z 0 0 0 1 0
# transformation
x <- x %*% t(x)
diag(x) <- 1
x
# X Y Z
#X 1 2 0
#Y 2 1 0
#Z 0 0 1
现在,我正在尝试将列c("A", "B", "C", "D", "E")
保留在矩阵中,如下所示:
Now, I'm trying to keep the columns c("A", "B", "C", "D", "E")
in the matrix, like this:
# X Y Z A B C D E
#X 1 0 0 1 1 0 0 0
#Y 0 1 0 1 1 0 0 0
#Z 0 0 1 0 0 0 1 0
#A 1 1 0 1 0 0 0 0
#B 1 1 0 0 1 0 0 0
#C 0 0 0 0 0 1 0 0
#D 0 0 1 0 0 0 1 0
#E 0 0 0 0 0 0 0 1
我敢肯定,有一种简单的方法可以做到,类似于第一个转换,包括每种情况.有人可以提出解决方案吗?
I'm pretty sure there's an easy way to do it similar to the first transformation including each case. Can anyone suggest a solution?
提前谢谢!
推荐答案
这只是一种扩充,不是吗?
This is just an augmentation, isn't it?
X <- as.matrix(x)
rbind(cbind(diag(nrow(X)), X), cbind(t(X), diag(ncol(X))))
这篇关于数据帧变成对称矩阵,同时保留所有行和列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文