建立对称的二进制矩阵 [英] Building a symmetric binary matrix

查看:60
本文介绍了建立对称的二进制矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的矩阵:

I have a matrix that is for example like this:

rownames    V1
a   1
c   3
b   2
d   4
y   2
q   4
i   1
j   1
r   3

我想制作一个对称的二进制矩阵,该矩阵的暗名与上述矩阵的行名相同.我想用1&填充这些矩阵0表示1表示放置在其前面具有相同编号的变量,而0表示相反的情况.该矩阵类似于

I want to make a Symmetric binary matrix that it's dimnames of that is the same as rownames of above matrix. I want to fill these matrix by 1 & 0 in such a way that 1 indicated placing variables that has the same number in front of it and 0 for the opposite situation.This matrix would be like

dimnames    
    a   c   b   d   y   q   i   j   r
a   1   0   0   0   0   0   1   1   0
c   0   1   0   0   0   0   0   0   1
b   0   0   1   0   1   0   0   0   0
d   0   0   0   1   0   1   0   0   0
y   0   0   1   0   1   0   0   0   0
q   0   0   0   1   0   1   0   0   0
i   1   0   0   0   0   0   1   1   0
j   1   0   0   0   0   0   1   1   0
r   0   1   0   0   0   0   0   0   1

有人知道我该怎么做吗?

Anybody know how can I do that?

推荐答案

使用 dist :

DF <- read.table(text = "rownames    V1
                 a   1
                 c   3
                 b   2
                 d   4
                 y   2
                 q   4
                 i   1
                 j   1
                 r   3", header = TRUE)

res <- as.matrix(dist(DF$V1)) == 0L
#alternatively:
#res <- !as.matrix(dist(DF$V1)) 
#diag(res) <- 0L #for the first version of the question, i.e. a zero diagonal
res <- +(res) #for the second version, i.e. to coerce to an integer matrix
dimnames(res) <- list(DF$rownames, DF$rownames)
#  1 2 3 4 5 6 7 8 9
#1 1 0 0 0 0 0 1 1 0
#2 0 1 0 0 0 0 0 0 1
#3 0 0 1 0 1 0 0 0 0
#4 0 0 0 1 0 1 0 0 0
#5 0 0 1 0 1 0 0 0 0
#6 0 0 0 1 0 1 0 0 0
#7 1 0 0 0 0 0 1 1 0
#8 1 0 0 0 0 0 1 1 0
#9 0 1 0 0 0 0 0 0 1

这篇关于建立对称的二进制矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆