R data.table子组计数和组摘要的加权百分比

时间:2018-04-06 19:16:47

标签: r data.table

我有以下data.table

n = 100000

DT = data.table(customer_ID = 1:n,
                married = rbinom(n, 1, 0.4),
                coupon = rbinom(n, 1, 0.15))

我需要创建一个表格,总结已婚和未婚客户的总数,使用优惠券的客户数量,婚姻状况子组和最后一列,用于计算按婚姻状况为每个子群使用优惠券的客户百分比。

输出应该看起来像这样。

   married Customers using Coupons Total Customers percent_usecoupon
1:       0                    9036           59790          15.11290
2:       1                    5943           40210          14.77991

我目前的代码效率非常低,而且我确信使用data.table有更好的语法,但我似乎无法找到它。我已经在下面复制了我当前的代码:

coupon_marital = DT[coupon == TRUE, .N, by = married][order(-N)] #Count of coupon use by marital status
total_marital = DT[, .N, by = married] #Total count by marital status
setnames(total_marital, "N", "Count") #Rename N to Count
coupon_marital = merge(coupon_marital, total_marital) #Merge data.tables

coupon_marital[, percent_usecoupon := N/Count*100, by = married] #Compute percentage coupon use
setnames(coupon_marital, c("N", "Count"), c("Customers using Coupons", "Total Customers")) #Rename N to Count
rm(total_marital)

print(coupon_marital)

我无法使用dplyr,只需要使用data.table。我对data.table语法相当新,非常感谢任何帮助!

1 个答案:

答案 0 :(得分:3)

创建数据

set.seed(10)
n = 100000
DT = data.table(customer_ID = 1:n,
                married = rbinom(n, 1, 0.4),
                coupon = rbinom(n, 1, 0.15))

汇总数据

DT[, .(N.UseCoupon   = sum(coupon)
      ,N.Total       = .N
      ,Pct.UseCoupon = 100*mean(coupon)), 
   by = married]

#    married N.UseCoupon N.Total Pct.UseCoupon
# 1:       0        8975   60223      14.90294
# 2:       1        5904   39777      14.84275