data.table 连接的排列

Permutations with data.table join

以下是客户 1 购买的 table 个产品。

df <- data.table(customer_id = rep(1,3)
                 , product_1 = letters[1:3]
                  )

   customer_id product_1
1:           1         a
2:           1         b
3:           1         c

假设真实数据集有多个客户,我想为每个客户创建一个 排列 每个人都购买过的产品(没有更换)。在组合学术语中:

nPk

哪里

n = 每个顾客购买的(不同的)产品数量

k = 2

结果:

customer_id product_1 product_2
1:           1         a         b
2:           1         a         c
3:           1         b         c
4:           1         b         a
5:           1         c         a
6:           1         c         b

SQL 加入条件为:

where   customer_id = customer_id
        and product_1 != product_1

不过,据我了解 data.table 目前有 limited support for non equi joins。因此,是否有其他方法可以实现此目的?

加入后可以消除product_1product_2相等的情况

df[df, on = .(customer_id = customer_id), allow.cartesian = T
   ][product_1 != i.product_1
     ][order(product_1)]

   customer_id product_1 i.product_1
1:           1         a           b
2:           1         a           c
3:           1         b           a
4:           1         b           c
5:           1         c           a
6:           1         c           b

使用与@Humpelstielzchen 相同的逻辑,在 dplyr 中我们可以使用 full_join

library(dplyr)
full_join(df, df, by = "customer_id") %>% filter(product_1.x != product_1.y)


#  customer_id product_1.x product_1.y
#1           1           a           b
#2           1           a           c
#3           1           b           a
#4           1           b           c
#5           1           c           a
#6           1           c           b

使用 by=.EACHI 的另一个选项:

df[df, on=.(customer_id), 
    .(p1=i.product_1, p2=x.product_1[x.product_1!=i.product_1]), by=.EACHI]

输出:

   customer_id p1 p2
1:           1  a  b
2:           1  a  c
3:           1  b  a
4:           1  b  c
5:           1  c  a
6:           1  c  b