Mode in R by groups

前端 未结 4 1345
余生分开走
余生分开走 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:45

    You can use dplyrfor this:

    library(dplyr)
    modes_by_age <- summarise(group_by(DT, age), group_mode = g(number))
    inner_join(DT, modes_by_age)
    

    This gives your desired output:

    Source: local data table [5 x 4]
    
      age         v number group_mode
    1   3 0.5524352      5          5
    2   3 0.2869912      5          5
    3  12 0.8987475    122        122
    4  12 0.9740715    125        122
    5  12 2.5058450    122        122
    

提交回复
热议问题