data.table: Sum by all existing combinations in table

前端 未结 2 653
温柔的废话
温柔的废话 2021-01-15 02:02

I have a data.table out like this (in reality it is much larger):

out <-      code weights group
        1:    2   0.387      1
        2:            


        
2条回答
  •  执念已碎
    2021-01-15 02:49

    I had a similar problem, and CJ did not work for some reason. A relatively simple solution I ended up using is first calling dcast and then melt (similar to the xtable solution above)- this also conveniently lets you specify the fill value for the missing combinations.

    sum.dt <- dcast(out, code ~ group, value.var = 'weights', 
                    fun.aggregate = sum, fill = 0)
    sum.dt <- melt(sum.dt, id.vars = 'code', variable.name = 'group')
    

    This gives

    > sum.dt
       code group value
    1:    1     1 0.399
    2:    2     1 1.997
    3:    3     1 0.000
    4:    1     2 0.212
    5:    2     2 0.373
    6:    3     2 1.322
    7:    1     3 0.474
    8:    2     3 0.569
    9:    3     3 0.316
    

提交回复
热议问题