Replacing values in a column where there is a match

后端 未结 5 1622
南旧
南旧 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条回答
  •  Happy的楠姐
    2021-01-22 07:15

    A base R approach that uses match

    df1$Category[match(df2$ID, df1$ID)] <- df2$Category
    df1
    #  ID Category
    #1  1   Cat600
    #2  2    CatVV
    #3  3   Cat611
    #4  4    CatQQ
    

    data

    df1 <- structure(list(ID = 1:4, Category = c("CatZZ", "CatVV", "CatAA", 
    "CatQQ")), .Names = c("ID", "Category"), class = "data.frame", row.names = c(NA, 
    -4L))
    
    df2 <- structure(list(ID = c(1L, 3L), Category = c("Cat600", "Cat611"
    )), .Names = c("ID", "Category"), class = "data.frame", row.names = c(NA, 
    -2L))
    

提交回复
热议问题