R data.table: porcentagem ponderada do subgrupo do grupo

eu tenho umdata.table gostar:

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) )

Embora eu não tenha certeza se este é o maisdata.table Dessa forma, posso calcular a frequência de subgrupos por grupo usandotable elength em uma única etapa - por exemplo, para responder à pergunta "Qual porcentagem de widgets vermelhos é redonda?"

editar: este código não fornece a resposta certa

# 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
# ...

Mas não posso usar essa abordagem para responder a perguntas como "Em peso, que porcentagem de widgets vermelhos é redonda?" Só posso pensar em uma abordagem em duas etapas:

# 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
# ...

Estou procurando uma abordagem de etapa única para B e A, se improvável, em uma explicação que aprofunda minha compreensão dedata.table sintaxe para operações por grupo. Observe que esta pergunta é diferente deSoma ponderada de variáveis por grupos com data.table porque o meu envolve subgrupos e evita várias etapas. TYVM.

questionAnswers(3)

yourAnswerToTheQuestion