【问题标题】:Create a binary adjacency matrix from a vector of indices从索引向量创建二进制邻接矩阵
【发布时间】:2017-07-25 19:28:43
【问题描述】:

假设我有一个看起来像这样的向量:

x <- sample(5, 500, replace = TRUE)

因此每个元素对应于从 1 到 5 的某个索引。

从这个向量创建二进制邻接矩阵的有效方法是什么?详细地说,矩阵A 应该是A[i,j] = 1 如果x[i] = x[j],否则为0。

【问题讨论】:

    标签: r matrix adjacency-matrix


    【解决方案1】:

    在一行中,你可以做到

    outer(x, x, function(x, y) as.integer(x==y))
    

    返回

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

    或者,分两行

    myMat <- outer(x, x, "==")
    myMat[] <- as.integer(myMat)
    

    检查它们是否相同。

    identical(myMat, outer(x, x, function(x, y) as.integer(x==y)))
    [1] TRUE
    

    数据

    set.seed(1234)
    x <- sample(5, 10, replace = TRUE)
    

    【讨论】:

    • 也可以sapply(seq_along(x), function(i) sapply(seq_along(x), function(j) as.integer(x[i] == x[j])))
    猜你喜欢
    • 2023-01-21
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-08
    • 2018-11-03
    • 1970-01-01
    相关资源
    最近更新 更多