11

是否有一种简单的方法可以将带有假人(二进制编码)的数据帧转换为包含两个方面同时出现的计数的共现矩阵?

例如,从此

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

对此

   X1 X2 X3 X4
X1  0  0  1  0
X2  0  0  2  1
X3  1  2  0  1
X4  0  1  1  0
4

2 回答 2

15

这可以解决问题:

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

要将结果完全像您展示的那样放入 data.frame 中,您可以执行以下操作:

nms <- paste("X", 1:4, sep="")
dimnames(out) <- list(nms, nms)
out <- as.data.frame(out)
于 2012-05-16T16:53:53.910 回答
0

虽然没有什么能比得上上面答案的简单性,只是发布tidyverse方法以供将来参考

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
于 2021-03-07T12:14:41.630 回答