Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a binary adjacency matrix from a vector of indices

Suppose I have a vector that looks like this:

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

so that each element corresponds to some index from 1 through 5.

What's an efficient way to create a binary adjacency matrix from this vector? To elaborate, the matrix A should be such that A[i,j] = 1 if x[i] = x[j] and 0 otherwise.

like image 624
user3294195 Avatar asked Mar 08 '23 12:03

user3294195


1 Answers

In one line, you could 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)

Check that they're the same.

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

data

set.seed(1234)
x <- sample(5, 10, replace = TRUE)
like image 150
lmo Avatar answered Mar 11 '23 00:03

lmo