r - Create a binary adjacency matrix from a vector of indices -
suppose have vector looks this:
x <- sample(5, 500, replace = true)
so each element corresponds index 1 through 5.
what's efficient way create binary adjacency matrix vector? elaborate, matrix a
should such a[i,j] = 1
if x[i] = x[j]
, 0 otherwise.
in 1 line, 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 2 lines
mymat <- outer(x, x, "==") mymat[] <- as.integer(mymat)
check they're 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)
Comments
Post a Comment