Create a binary adjacency matrix from an index vector

Suppose I have a vector that looks like this:

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

so that each element corresponds to a certain index from 1 to 5.

What is an effective way to create a binary adjacency matrix from this vector? To develop, the matrix Amust be such that A[i,j] = 1if x[i] = x[j]and 0 otherwise.

+4
source share
1 answer

In one line you can do

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

which returns

     [,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

or, in two lines

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

Make sure they are the same.

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

<strong> data

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

Source: https://habr.com/ru/post/1682255/


All Articles