gpt4 book ai didi

r - 如何计算表中的共现率?

转载 作者:行者123 更新时间:2023-12-02 01:13:01 24 4
gpt4 key购买 nike

我有一个简单的矩阵,例如

test <- matrix(c("u1","p1","u1","p2","u2","p2","u2",
"p3","u3","p1","u4","p2","u5","p1",
"u5","p3","u6","p3","u7","p4","u7",
"p3","u8","p1","u9","p4"),
ncol=2,byrow=TRUE)
colnames(test) <- c("user","product")
test1<-as.data.frame(test)

测试:

   user   product
1 u1 p1
2 u1 p2
3 u2 p2
4 u2 p3
5 u3 p1
6 u4 p2
7 u5 p1
8 u5 p3
9 u6 p3
10 u7 p4
11 u7 p3
12 u8 p1
13 u9 p4

我想统计有多少用户同时购买了产品对,例如p1&p2、p2&p3...

table(test1$product,test1$product)给我这个:

     p1   p2  p3  p4
p1 4 0 0 0
p2 0 3 0 0
p3 0 0 4 0
p4 0 0 0 2

我怎样才能得到正确的结果:

     p1   p2  p3  p4
p1 4 1 1 0
p2 1 3 1 0
p3 1 1 4 1
p4 0 0 1 2

最佳答案

查看所需的输出,您正在寻找 crossprod 函数:

crossprod(table(test1))
# product
# product p1 p2 p3 p4
# p1 4 1 1 0
# p2 1 3 1 0
# p3 1 1 4 1
# p4 0 0 1 2

这与 crossprod(table(test1$user, test1$product)) 相同(反射(reflect) Dennis 的评论)。

关于r - 如何计算表中的共现率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19977596/

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