R数据表子组计数和组汇总的加权百分比
我有以下数据表R数据表子组计数和组汇总的加权百分比,r,data.table,R,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 usi
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语法相当陌生,非常感谢您的帮助 创建数据
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
创建数据
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
平均值的使用是智能的。不确定是否有其他选项继续使用[,(N.usetucon,N.Total,Pct.usetucon=100*N.usetucon/N.Total]
有效。这太完美了!非常感谢!@MKR Re efficiency,查看?GForce
我想在后面做第三列应该是最有效的DT[,(s=sum(x),N=N),by=g][,p:=s/n*100]
使用平均值
是智能的。不确定是否有其他选项继续使用[,。(n.useCoup,n.Total,Pct.useCoup=100*n.useCoup/n.Total)
非常有效。这太完美了!非常感谢!@MKR Re efficiency,看看?GForce
我想在后面做第三列应该是最有效的DT[,(s=sum(x),n=.n),by=g][,p:=s/n*100]