根据部分信息生成完整的邻接矩阵

时间:2019-02-18 22:34:32

标签: r igraph data-manipulation adjacency-matrix

I have一个矩阵,其中包含构造5x5邻接矩阵所需的所有信息。每行代表一个矩阵:

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    1    1    1    1    1    1    1    0    1     0
[2,]    0    0    0    1    1    1    1    0    1     0
...

I want从数据的第n行创建一个邻接矩阵。对于have的第一行,want矩阵如下所示:

     [,1] [,2] [,3] [,4] [,5]
[1,]    0    1    1    1    1
[2,]    1    0    1    1    1
[3,]    1    1    0    0    1
[4,]    1    1    0    0    0
[5,]    1    1    1    0    0

如何从havewant

1 个答案:

答案 0 :(得分:4)

这里是使用lower.triupper.tri的选项

unlist(apply(mat, 1, function(x) {
    m <- matrix(0, nrow = 5, ncol = 5)
    m[lower.tri(m)] <- x
    m[upper.tri(m)] <- x
    list(m)
}), recursive = F)
#[[1]]
#     [,1] [,2] [,3] [,4] [,5]
#[1,]    0    1    1    1    1
#[2,]    1    0    1    1    0
#[3,]    1    1    0    1    1
#[4,]    1    1    0    0    0
#[5,]    1    1    1    0    0
#
#[[2]]
#     [,1] [,2] [,3] [,4] [,5]
#[1,]    0    0    0    1    1
#[2,]    0    0    0    1    0
#[3,]    0    1    0    1    1
#[4,]    0    1    0    0    0
#[5,]    1    1    1    0    0

unlist(..., recursive = F)部分看起来有些尴尬,但对于防止apply简化结果并减少暗淡是必不可少的。一种替代方法是在lapply上使用data.frame而不是matrix

lapply(as.data.frame(t(mat)), function(x) {
    m <- matrix(0, nrow = 5, ncol = 5)
    m[lower.tri(m)] <- x
    m[upper.tri(m)] <- x
    return(m)
})

给出相同的结果。


样本数据

mat <- as.matrix(read.table(text =
"1    1    1    1    1    1    1    0    1     0
0    0    0    1    1    1    1    0    1     0", header = F))
colnames(mat) <- NULL