Select only the first row when merging data frames with multiple matches

后端 未结 4 775
醉梦人生
醉梦人生 2020-12-03 07:52

I have two data frames, \"data\" and \"scores\", and want to merge them on the \"id\" column:

data = data.frame(id = c(1,2,3,4,5),
                  state =          


        
4条回答
  •  心在旅途
    2020-12-03 08:41

    In base you can use match to Select only the first row when merging data frames with multiple matches.

    #Return also those which found no match
    (tt <- cbind(data, score=scores[match(data$id, scores$id),"score"]))
    #  id state score
    #1  1    KS    66
    #2  2    MN    86
    #3  3    AL    76
    #4  4    FL    NA
    #5  5    CA    NA
    
    #Return only those which found a match
    tt[!is.na(tt$score),]
    #  id state score
    #1  1    KS    66
    #2  2    MN    86
    #3  3    AL    76
    

提交回复
热议问题