Mode in R by groups

前端 未结 4 1356
余生分开走
余生分开走 2020-12-19 20:08

I need to calculate the mode of an identity number for each group of ages. Let\'s suposse the following table:

library(data.table)
DT = data.table(age=c(12,1         


        
4条回答
  •  清酒与你
    2020-12-19 20:55

    Here's a base R solution. You could compute the mode for each group and then merge with your original data:

    merge(DT, setNames(aggregate(number~age, data=DT, g), c("age", "moda")), by="age")
    #    age          v number moda
    # 1:   3  1.7148357      5    5
    # 2:   3  0.9504811      5    5
    # 3:  12 -0.7648237    122  122
    # 4:  12  0.9011115    125  122
    # 5:  12 -0.8718779    122  122
    

    There may be a data table-specific approach, but this would work even if DT were a data frame.

提交回复
热议问题