【问题标题】:R cumulative distinct count customer and productsR 累积可区分计数客户和产品
【发布时间】:2016-01-31 22:49:37
【问题描述】:

我有一个带有客户 ID 的已售 sku 数据集。

dtSales = data.table(sku = c("a", "b", "b", "c", "b","b", "c", "d", "b", "a"),
                 qty = c(1,1,1,2,1,3,2,1,4,2),
                 customer = c(1,1,2,2,3,1,1,1,4,1))

    id sku qty customer
1:  1   a   1        1
2:  2   b   1        1
3:  3   b   1        2
4:  4   c   2        2
5:  5   b   1        3
6:  6   b   3        1
7:  7   c   2        1
8:  8   d   1        1
9:  9   b   4        4
10: 10   a   2        1

我可以找到每个 sku 被购买了多少次,以及有多少客户购买了每个产品。

dtSales[,.(ttlqty=sum(qty), distinctCustomer= length(unique(customer))) ,by=sku][order(-ttlqty)]

    sku ttlqty distinctCustomer
1:   b     10                4
2:   c      4                2
3:   a      3                1
4:   d      1                1

我想对客户进行累计计数。 第一行:有多少不同的客户购买了产品 1 第二行:有多少不同的客户购买了产品 1 或产品 2 ...

谢谢

【问题讨论】:

  • 查看cumsum 并将其应用于您的 distinctCustomer 列,您应该得到所需的输出?
  • 我不想简单地添加 distinctCustomer 列,我想找到购买过任何以前产品的不同客户。因此,如果客户 1 购买了产品 b 和 c,我只想计算他一次。
  • 为了有人能帮到你,我相信你应该根据你上面发布的输入更新你的问题的细节和所需的输出。

标签: r data.table


【解决方案1】:

听起来好像您想要一个累积的客户联盟。 Reduceaccumulate=TRUE可以进行累积运算

(cu<-Reduce(function(x,y) union(x,y),
   Map(unique,split(df$customer,df$sku)), acc=TRUE))

按照与levels(df$sku)相同的顺序生成购买产品a、产品ab等的客户的累积联合。

[[1]] [1] 1 [[2]] [1] 1 2 3 4 [[3]] [1] 1 2 3 4 [[4]] [1] 1 2 3 4

最后,我们可以得到每个的长度并放在关卡旁边

data.frame(sku=levels(df$sku),cc=sapply(cu,length))  
货号抄送 1 一 1 2 b 4 3 c 4 4 天 4

请注意,我自始至终都使用了data.frames 和基本函数。

【讨论】:

    【解决方案2】:

    感谢 A. Webb。指向Reduce。我想让结果从最畅销的产品到最畅销的产品进行排序,所以我进行了调整。

    最终解决方案

    library(data.table)
    
    
    dtSales = data.table(sku = c("a", "b", "b", "c", "b","b", "c", "d", "c", "a"),
                         qty = c(1,1,1,2,1,3,2,1,4,2),
                         customer = c(1,1,2,2,3,1,1,1,4,1))
    
    #convert sku column to factor
    dtSales$sku <- as.factor(dtSales$sku)
    
    #find how many times each sku was bought and sort from high to low
    orderedSku = dtSales[,.(ttlqty=sum(qty), distinctCustomer= length(unique(customer))) ,by=sku][order(-ttlqty)]
    
    #order the sku from most sold to less sold
    dtSales$sku <- factor(dtSales$sku, levels= orderedSku$sku)
    
    #cumulative distinct count of customers
    cu<-Reduce(function(x,y) union(x,y), Map(unique,split(dtSales$customer, dtSales$sku)), acc=TRUE)
    
    #merge the results
    data.frame(sku=levels(dtSales$sku), qty=orderedSku$ttlqty, cc=sapply(cu,length))  
    

    【讨论】:

      猜你喜欢
      • 2021-06-18
      • 2021-07-21
      • 1970-01-01
      • 1970-01-01
      • 2017-03-07
      • 1970-01-01
      • 2020-11-21
      • 1970-01-01
      • 2019-03-30
      相关资源
      最近更新 更多