Subset data based on Minimum Value

后端 未结 2 1948
清酒与你
清酒与你 2020-12-21 13:32

This might an easy one. Here\'s the data:

dat <- read.table(header=TRUE, text=\"
Seg  ID  Distance
Seg46      V21 160.37672
Seg72      V85 191.24400
Seg37         


        
2条回答
  •  再見小時候
    2020-12-21 14:34

    We can subset the rows with which.min. After grouping with 'ID', we slice the rows based on the position of minimum 'Distance'.

    library(dplyr)
    dat %>% 
       group_by(ID) %>% 
       slice(which.min(Distance))
    

    A similar option using data.table would be

    library(data.table)
    setDT(dat)[, .SD[which.min(Distance)], by = ID]
    

提交回复
热议问题