How to use R for same field aggregation by multiple separate group

前端 未结 2 346
梦毁少年i
梦毁少年i 2020-12-21 14:01

I\'m trying to perform count of an indicator on several (actually hundreds) groups separately (NOT on all combinations of all groups). I\'ll demonstrate it by simplified exa

2条回答
  •  盖世英雄少女心
    2020-12-21 14:41

    melt from "reshape2" has a method for matrices which could be useful here. Using "reshape2", the solution could be as straightforward as:

    library(reshape2)
    dcast(cbind(some_indicator, melt(data)), 
          value ~ Var2, value.var= "some_indicator", 
          fun.aggregate=sum)
    #   value 1 2 3
    # 1     1 1 1 0
    # 2     2 2 1 1
    # 3     3 0 1 2
    

    This answer assumes some prior knowledge of how melt works on a matrix, in particular that it will create a three-column data.frame with "Var1" representing the rownames (or numbers), "Var2" representing the colnames (or numbers), and "value" representing the values from the matrix.

提交回复
热议问题