我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) )
Run Code Online (Sandbox Code Playgroud)
虽然我不知道这是最data.table方式,我可以使用组计算群的频率table和length在例如单step--,要回答这个问题:"是什么圆百分之红色小部件?"
编辑:此代码未提供正确答案
# 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
# ...
Run Code Online (Sandbox Code Playgroud)
但我不能用这种方法回答诸如"按重量,红色小部件的百分比是多少?"之类的问题.我只能提出两步法:
# 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: …Run Code Online (Sandbox Code Playgroud)