亚组加权百分比我有一个像data.table
:[R data.table:
library(data.table)
widgets <- data.table(serial_no=1:100,
color=rep_len(c("red","green","blue","black"),length.out=100),
style=rep_len(c("round","pointy","flat"),length.out=100),
weight=rep_len(1:5,length.out=100))
虽然我不知道这是最data.table
的方式,我可以使用table
和length
计算按组群频率只需一个步骤 - 例如,回答“红色小部件百分之几是圆的?”的问题。
编辑:这个代码不提供正确的答案
# example A
widgets[, list(style = unique(style),
style_pct_of_color_by_count =
as.numeric(table(style)/length(style))), by=color]
# color style style_pct_of_color_by_count
# 1: red round 0.32
# 2: red pointy 0.32
# 3: red flat 0.36
# 4: green pointy 0.32
# ...
但我不能用这种方法来回答这样的问题“按重量计算,百分之多少的红色部件是圆的?”我只能想出一个两步走的方法:
# example B
widgets[,list(cs_weight=sum(weight)),by=list(color,style)][,list(style, style_pct_of_color_by_weight=cs_weight/sum(cs_weight)),by=color]
# color style style_pct_of_color_by_weight
# 1: red round 0.3466667
# 2: red pointy 0.3466667
# 3: red flat 0.3066667
# 4: green pointy 0.3333333
# ...
我正在寻找一个单一步骤的方法,以B,和A如果改善的,在加深我的理解data.table
语法为副解释集团运营。请注意,这个问题与Weighted sum of variables by groups with data.table不同,因为我涉及子组并避免多个步骤。 TYVM。
看着从@Frank响应下面我发现我的尝试不仅是尴尬,但不正确 - 例如,我检查'小部件[,总和(style ==“round”&color ==“red”)/ sum(color ==“red”)]#0.36' – C8H10N4O2