gpt4 book ai didi

r - 从虚拟编码观察创建共现矩阵

转载 作者:行者123 更新时间:2023-12-02 18:15:14 25 4
gpt4 key购买 nike

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

例如从此开始

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

最佳答案

这就能解决问题:

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)

关于r - 从虚拟编码观察创建共现矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10622730/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com