Create a co-occurrence matrix from dummy-coded observations

This will do the trick:

X <- as.matrix(X)
out <- crossprod(X)  # Same as: t(X) %*% X
diag(out) <- 0       # (b/c you don't count co-occurrences of an aspect with itself)
out
#      [,1] [,2] [,3] [,4]
# [1,]    0    0    1    0
# [2,]    0    0    2    1
# [3,]    1    2    0    1
# [4,]    0    1    1    0

To get the results into a data.frame exactly like the one you showed, you can then do something like:

nms <- paste("X", 1:4, sep="")
dimnames(out) <- list(nms, nms)
out <- as.data.frame(out)

Leave a Comment