我的数据集如下:
Product_1 Product_2
A B
A A
A C
C D
B C
E E
Z Z
表格说的是,实际上产品A是产品B,然后产品A当然是产品A,产品A也与产品C相同,但考虑到最终产品A中产品C是产品D也与产品相同D.
我需要在此表中添加一列,以将所有相同的产品分组,如下所示:
Product_1 Product_2 Group
A B 1
A A 1
A C 1
C D 1
B C 1
E E 2
Z Z 3
我正在使用R,因此我正在考虑对软件包sqldf使用递归CTE。
它是大数据,因此使用矩阵来解决问题将使我超过1.3 TB的存储容量。
有人知道怎么做吗?
最佳答案
此关系为commutative,因此b
计算两个方向的关系,以简化以下查询。closure
是递归CTE,并计算transitive closure,即等效产品的所有可能组合。ec
计算equivalence classes,即,对于每个产品,它都会计算同一类别中最小的产品名称,例如:
A|A B|A C|A D|A E|E Z|Z
g
computes the group number by counting how many smaller distinct class
values there are:
A|1 B|1 C|1 D|1 E|2 Z|3
WITH RECURSIVE b AS (
SELECT product_1, product_2 FROM MyTable
UNION ALL
SELECT product_2, product_1 FROM MyTable
),
closure AS (
SELECT product_1, product_2 FROM b
UNION
SELECT c.product_1, b.product_2
FROM closure AS c
JOIN b ON c.product_2 = b.product_1
),
ec(product, class) AS (
SELECT product_1, MIN(product_2)
FROM closure
GROUP BY product_1
),
g(product, g) AS (
SELECT product,
(SELECT COUNT(DISTINCT class)
FROM ec AS ec2
WHERE ec2.class <= ec.class)
FROM ec
)
UPDATE MyTable
SET "Group" = (SELECT g
FROM g
WHERE product = MyTable.Product_1);
大数据
然后,我们希望您有一个大磁盘来存放临时数据……
关于sql - 对数据集中的唯一数字组进行递归CTE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47030724/