Replacing values in a column where there is a match

后端 未结 5 1595
南旧
南旧 2021-01-22 06:48

I\'m new to R programming and I\'m stuck on the example below.

Basically I have two data sets:

dataset1:

ID       Category        
1        CatZ         


        
5条回答
  •  佛祖请我去吃肉
    2021-01-22 07:27

    You can stack df2 on top of df1 and keep the first instance for each ID.

    With tidyverse that would be :

    library(tidyverse)
    bind_rows(df2,df1) %>%
      group_by(ID) %>%
      slice(1) %>%
      ungroup()
    
    # # A tibble: 4 x 2
    #      ID Category
    #       
    # 1     1   Cat600
    # 2     2    CatVV
    # 3     3   Cat611
    # 4     4    CatQQ
    

    Or a base version (which reorders the rows) :

    subset(rbind(df2,df1), !duplicated(ID))
    #   ID Category
    # 1  1   Cat600
    # 2  3   Cat611
    # 4  2    CatVV
    # 6  4    CatQQ
    

提交回复
热议问题