多个变量的对组合计数

Tally of pair combinations for multiple variables

我有一个数据集,其中每一列都有 4 个二进制变量。我如何使用每对变量组合的计数创建 4 x 4 网格?

这是一个示例数据框:

Person <- c("Bob", "Jim", "Sarah", "Dave")
A <- c(1,0,1,1)
B <- c(1,1,1,0)
C <- c(0,0,0,1)
D <- c(1,0,0,0)

所以在 4x4 网格中,A 和 B 的交集会是 2,因为 Bob 和 Sarah 的 A 和 B 是 1。

对于两个向量 AB 它将是叉积:

res <- A %*% B 要么 res <- crossprod(A, B)

要使所有组合的矩阵使用两个级别 forapply:

data <- list(A,B,C,D)
res <- matrix(NA, nrow = n, ncol = m, dimnames = dimnames(product.m))

for(i in 1:n) {
  for(j in 1:i) {
    res[i,j] <- crossprod(data[[i]], data[[j]])
  }
}

这里我只填了矩阵的一半。然后您可以像这样复制值:

res[upper.tri(res)] <- t(res)[upper.tri(res)]