【问题标题】:Permutations with data.table join与 data.table 连接的排列
【发布时间】:2019-08-19 09:08:24
【问题描述】:

下面是客户 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

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

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。因此,是否有其他方法可以实现这一目标?

【问题讨论】:

  • 这可以通过非 equi 连接来完成。

标签: r data.table combinatorics


【解决方案1】:

加入后可以排除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 为什么data.table 不允许以下内容? df[df, on = .(customer_id = customer_id , product_1 != i.product_1), allow.cartesian = T ] 因此,需要链接?
  • 说实话,我不知道为什么data.table join 语法中没有!=
【解决方案2】:

另一个使用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

【讨论】:

  • 这也有效。但是,方法(语法)对我来说是新的。我需要自己解析它。谢谢@chinsoon12
【解决方案3】:

使用与@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

【讨论】:

  • 谢谢@Ronak,我正在寻找data.table 解决方案以提高性能。虽然非常感谢
猜你喜欢
  • 1970-01-01
  • 2015-12-25
  • 1970-01-01
  • 2021-03-08
  • 2018-11-13
  • 2022-11-22
  • 2016-11-03
  • 2012-04-12
  • 2020-12-16
相关资源
最近更新 更多