简体   繁体   中英

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM