R, conditionally remove duplicate rows

主宰稳场 提交于 2019-11-29 04:22:26

You can also do it easily in base R. If dat is your dataframe,

do.call(rbind, 
        by(dat, INDICES=list(dat$ID.A), 
           FUN=function(x) head(x[order(x$DISTANCE), ], 1)))

One possibility:

myDF <- myDF[order(myDF$ID.A, myDF$DISTANCE), ] 

newdata <- myDF[which(!duplicated(myDF$ID.A)),]

Which gives :

    ID.A ID.B DISTANCE
1    1    3      1.0
2    2    6      8.0
5    3    2      0.4
6    4    8      7.0
7    5    2     11.0

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!