相关疑难解决方法(0)

R data.table:组的子组加权百分比

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方式,我可以使用组计算群的频率tablelength在例如单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)

grouping r data.table

8
推荐指数
1
解决办法
4019
查看次数

标签 统计

data.table ×1

grouping ×1

r ×1