我有数据框,表示客户是否购买了某些商品。 df如下所示:
P1 P2 P3 P4 P5
1 2 0 0 0
1 1 0 0 0
0 0 0 3 0
1 0 0 1 0
1 0 5 1 0
1 1 0 0 0
我正在尝试创建在表格中购买每个项目对的家庭数量。结果的快照将是:
P1 P2 3
P1 P3 1
P1 P4 2
---------
作为第一步,我将数据转换为二进制格式 - 如果购买了该项目。然而,我正在努力将其转换为项目对组的功能。
---我希望使用这些数据创建一个网络图,所以也许创建一个矩阵也可以使用
答案 0 :(得分:3)
调用您的数据d
:
d = structure(list(P1 = c(1L, 1L, 0L, 1L, 1L, 1L), P2 = c(2L, 1L,
0L, 0L, 0L, 1L), P3 = c(0L, 0L, 0L, 0L, 5L, 0L), P4 = c(0L, 0L,
3L, 1L, 1L, 0L), P5 = c(0L, 0L, 0L, 0L, 0L, 0L)), .Names = c("P1",
"P2", "P3", "P4", "P5"), class = "data.frame", row.names = c(NA,
-6L))
我们可以使用combn
:
pairs = combn(x = names(d), m = 2)
counts = combn(x = names(d), m = 2, FUN = function(x) sum(d[[x[1]]] > 0 & d[[x[2]]] > 0))
cbind.data.frame(t(pairs), counts)
# 1 2 counts
# 1 P1 P2 3
# 2 P1 P3 1
# 3 P1 P4 2
# 4 P1 P5 0
# 5 P2 P3 0
# 6 P2 P4 0
# 7 P2 P5 0
# 8 P3 P4 1
# 9 P3 P5 0
# 10 P4 P5 0
答案 1 :(得分:2)
首先制作列名的所有成对组合:
res <- as.data.frame( t( combn(names(dat),2)))
然后对销售的两列中的存在进行逐行求和:
res$counts <- apply(res, 1, function(rw) sum(
pmin( as.logical(dat[ ,rw[1] ]), #rw[1] is col name
as.logical(dat[ , rw[2] ]) # 2nd col name
) ) )
> res
V1 V2 counts
1 P1 P2 3
2 P1 P3 1
3 P1 P4 2
4 P1 P5 0
5 P2 P3 0
6 P2 P4 0
7 P2 P5 0
8 P3 P4 1
9 P3 P5 0
10 P4 P5 0
答案 2 :(得分:1)
您可以使用combn()
构建此代码:
as.data.frame(t(combn(names(df),2, function(x) list(x[1], x[2], sum((df[,x[1]]*df[,x[2]])!=0)))))
V1 V2 V3
1 P1 P2 3
2 P1 P3 1
3 P1 P4 2
4 P1 P5 0
5 P2 P3 0
6 P2 P4 0
7 P2 P5 0
8 P3 P4 1
9 P3 P5 0
10 P4 P5 0