Aggregate by factor levels, keeping other variables in the resulting data frame

前端 未结 5 2076
太阳男子
太阳男子 2020-12-05 18:45

I\'m trying to calculate the minimum values of a numeric column for each level of a factor, while keeping values of another factor in the resulting data frame.



        
5条回答
  •  -上瘾入骨i
    2020-12-05 19:23

    With the dplyr and data.table packages, you can do the following. You can get an index for the row having the minimum value for each group. You can use that in slice() if you use dplyr. You can achieve the same subsetting using .SD if you use data.table.

    library(dplyr)
    library(data.table)
    
    dat %>%
    group_by(code) %>%
    slice(which.min(value))
    
    #    code   index value
    #     
    #1   HH11  023434  24.1
    #2   HH45 3377477  37.2
    #3   JL03 1177777  20.0
    
    setDT(dat)[, .SD[which.min(value)], by = code]
    
    #   code   index value
    #1: HH11  023434  24.1
    #2: HH45 3377477  37.2
    #3: JL03 1177777  20.0
    

提交回复
热议问题