R, conditionally remove duplicate rows

前端 未结 3 691
天涯浪人
天涯浪人 2020-12-09 20:17

I have a dataframe in R containing the columns ID.A, ID.B and DISTANCE, where distance represents the distance between ID.A and ID.B. For each value (1->n) of ID.A, there ma

3条回答
  •  暖寄归人
    2020-12-09 20:55

    You can use the plyr package for that. For example, if your data are like these :

    d <- data.frame(id.a=c(1,1,1,2,2,3,3,3,3),
                    id.b=c(1,2,3,1,2,1,2,3,4),
                    dist=c(12,10,15,20,18,16,17,25,9))
    
      id.a id.b dist
    1    1    1   12
    2    1    2   10
    3    1    3   15
    4    2    1   20
    5    2    2   18
    6    3    1   16
    7    3    2   17
    8    3    3   25
    9    3    4    9
    

    You can use the ddply function like this :

    library(plyr)
    ddply(d, "id.a", function(df) return(df[df$dist==min(df$dist),]))
    

    Which gives :

      id.a id.b dist
    1    1    2   10
    2    2    2   18
    3    3    4    9
    

提交回复
热议问题