R:哪些产品更经常一起购买?

R:哪些产品更经常一起购买?,r,R,我有一个客户数据,上面列出了他们购买的产品。它只考虑他们是否买。这不包括他们买了多少。(对于条目,so 0或1) 我想知道这些产品中哪些可能一起销售 我能想到的是考虑所有排列,相应地创建变量,并总结个人。 a a_b a_c b b_c a_b_c 1 0 0 1 0 0 0 2 0 0 0 1 0 0 3 0 0 0 0 0 1 4 0 0 0 0 0

我有一个客户数据,上面列出了他们购买的产品。它只考虑他们是否买。这不包括他们买了多少。(对于条目,so 0或1)

我想知道这些产品中哪些可能一起销售

我能想到的是考虑所有排列,相应地创建变量,并总结个人。

    a   a_b  a_c  b   b_c  a_b_c
1   0   0    1    0   0    0
2   0   0    0    1   0    0
3   0   0    0    0   0    1
4   0   0    0    0   0    0
5   0   0    1    0   0    0
sum 0   0    2    1   0    1
所以在这个小例子中,人们喜欢一起买苹果和玉米

我试着用下面的方法来做,但是重复的代码会变得非常麻烦

allCombs <- function(x) c(x, lapply(seq_along(x)[-1L], function(y) combn(x, y, paste0, collapse = "_")),recursive = TRUE)
name = c("a","b","c")
for (i in allCombs(name)) {
  df[,i] = 0
}
condition_1 = df[,"apple"] == 1
condition_2 = df[,"banana"] == 1
condition_3 = df[,"corn"] == 1
df[condition_1 & !condition_2 & !condition_3, "a"] = 1
df[condition_1 & condition_2 & !condition_3, "a_b"] = 1
...

allCombs只需调用
,即可解决此问题:

DF <- read.table(text = "   apple banana corn
1  1     0      1
2  0     1      0
3  1     1      1
4  0     0      0
5  1     0      1", header = TRUE)

as.data.frame(do.call(table, DF))
#  apple banana corn Freq
#1     0      0    0    1
#2     1      0    0    0
#3     0      1    0    1
#4     1      1    0    0
#5     0      0    1    0
#6     1      0    1    2
#7     0      1    1    0
#8     1      1    1    1

DF只需调用
,即可解决此问题:

DF <- read.table(text = "   apple banana corn
1  1     0      1
2  0     1      0
3  1     1      1
4  0     0      0
5  1     0      1", header = TRUE)

as.data.frame(do.call(table, DF))
#  apple banana corn Freq
#1     0      0    0    1
#2     1      0    0    0
#3     0      1    0    1
#4     1      1    0    0
#5     0      0    1    0
#6     1      0    1    2
#7     0      1    1    0
#8     1      1    1    1
DF
DF <- read.table(text = "   apple banana corn
1  1     0      1
2  0     1      0
3  1     1      1
4  0     0      0
5  1     0      1", header = TRUE)

as.data.frame(do.call(table, DF))
#  apple banana corn Freq
#1     0      0    0    1
#2     1      0    0    0
#3     0      1    0    1
#4     1      1    0    0
#5     0      0    1    0
#6     1      0    1    2
#7     0      1    1    0
#8     1      1    1    1
pairs1 <- combn(DF, 2, function(x) x[1] == 1 & x[1] == x[2], simplify = FALSE)
pairs2 <- combn(names(DF), 2)
paircounts <- data.frame(t(pairs2), freq = sapply(pairs1, sum))
#      X1     X2 freq
#1  apple banana    1
#2  apple   corn    3
#3 banana   corn    1