11

Is there a simple approach to converting a data frame with dummies (binary coded) on whether an aspect is present, to a co-occurrence matrix containing the counts of two aspects co-occuring?

E.g. going from this

X <- data.frame(rbind(c(1,0,1,0), c(0,1,1,0), c(0,1,1,1), c(0,0,1,0)))
X
  X1 X2 X3 X4
1  1  0  1  0
2  0  1  1  0
3  0  1  1  1
4  0  0  1  0

to this

   X1 X2 X3 X4
X1  0  0  1  0
X2  0  0  2  1
X3  1  2  0  1
X4  0  1  1  0
Henrik
  • 61,039
  • 13
  • 131
  • 152
mhermans
  • 2,007
  • 4
  • 18
  • 31

2 Answers2

15

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)
Josh O'Brien
  • 154,425
  • 26
  • 353
  • 447
0

Though nothing can match the simplicity of answer above, just posting tidyverse aproach for future reference

Y <- X %>% mutate(id = row_number()) %>%
  pivot_longer(-id) %>% filter(value !=0)

merge(Y, Y, by = "id", all = T) %>%
  filter(name.x != name.y) %>%
  group_by(name.x, name.y) %>%
  summarise(val = n()) %>%
  pivot_wider(names_from = name.y, values_from = val, values_fill = 0, names_sort = T) %>%
  column_to_rownames("name.x")

   X1 X2 X3 X4
X1  0  0  1  0
X2  0  0  2  1
X3  1  2  0  1
X4  0  1  1  0
AnilGoyal
  • 23,996
  • 4
  • 21
  • 40