【发布时间】:2015-09-05 18:56:39
【问题描述】:
我有一个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 的回复,我注意到我的尝试A 不仅尴尬而且不正确——例如,我检查了
widgets[,sum(style=="round" & color=="red")/sum(color=="red")] # 0.36
标签: r data.table grouping