使用 data.table 连接进行排列

T.F*_*ung 3 r combinatorics data.table

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

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
Run Code Online (Sandbox Code Playgroud)

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

nPk
Run Code Online (Sandbox Code Playgroud)

在哪里

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
Run Code Online (Sandbox Code Playgroud)

SQL 连接条件为:

where   customer_id = customer_id
        and product_1 != product_1
Run Code Online (Sandbox Code Playgroud)

但是,我知道data.table目前对 non equi joins 的支持有限。因此,有没有其他方法可以实现这一目标?

Hum*_*hen 5

您可以消除加入后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
Run Code Online (Sandbox Code Playgroud)

  • 老实说,我不知道为什么`data.table`连接语法中没有`!=` (2认同)