根据匹配的列值将值分配给空的邻接矩阵

时间:2015-07-20 01:50:55

标签: r

我有一个nxn数据集,比如5X5数据集。

ALPHA   BETA    GAMMA   DELTA   EPSILON
A       B       A       X       1
B       C       3       X       3
C       D       E       Z       4
D       A       D       X       5
E       A       2       Z       2

我使用列“ALPHA”来创建一个空的邻接矩阵(Aij),

    A   B   C   D   E
A   0   0   0   0   0
B   0   0   0   0   0
C   0   0   0   0   0
D   0   0   0   0   0
E   0   0   0   0   0

我想根据列“DELTA”的匹配值将邻接矩阵值重新分配为1或0,这样,如果“DELTA”匹配,我们设置Aij = 1,否则为0。也就是说,我们将有一个新的邻接矩阵,如下所示,

    A   B   C   D   E
A   0   1   0   1   0
B   1   0   0   1   0
C   0   0   0   0   1
D   1   1   0   0   0
E   0   0   1   0   0

我可以使用什么循环命令或匹配技术来分配新值?

感谢。 菲尔

2 个答案:

答案 0 :(得分:1)

循环可以工作。在示例中,A(i = j)为0,因此我减去了对角矩阵

DELTA<-c("X","X","Z","X","Z")
Adj<-mat.or.vec(nr=length(DELTA), nc=length(DELTA))
for (i in 1:length(DELTA)){
    Adj[i,DELTA==DELTA[i]]<-1
}
Adj<-Adj-diag(length(DELTA))

答案 1 :(得分:0)

您可以使用outer

 res <- +(outer(df1$DELTA, df1$DELTA, FUN='=='))*!diag(dim(df1)[1])
 dimnames(res) <- rep(list(df1$ALPHA),2)
 res
 #  A B C D E
 #A 0 1 0 1 0
 #B 1 0 0 1 0
 #C 0 0 0 0 1
 #D 1 1 0 0 0
 #E 0 0 1 0 0

或者

  sapply(df1$DELTA, `==`, df1$DELTA) - diag(dim(df1)[1])

数据

 df1 <- structure(list(ALPHA = c("A", "B", "C", "D", "E"), BETA = c("B", 
 "C", "D", "A", "A"), GAMMA = c("A", "3", "E", "D", "2"), DELTA = c("X", 
 "X", "Z", "X", "Z"), EPSILON = c(1L, 3L, 4L, 5L, 2L)), .Names = c("ALPHA", 
 "BETA", "GAMMA", "DELTA", "EPSILON"), class = "data.frame", 
 row.names = c(NA, -5L))