Join and overwrite data in one table with data from another table

后端 未结 3 2014
生来不讨喜
生来不讨喜 2021-01-14 07:57

How to join and overwrite data appears to be a common request, but I have yet to find an elegant solution that applies to an entire dataset.

(Note: to simplify the d

3条回答
  •  礼貌的吻别
    2021-01-14 08:31

    Here's @Frank's solution from the comments. (Note: d1 and d2 need to be defined as data.table first).

    library(data.table)
    cols = setdiff(intersect(names(d1), names(d2)), "id") 
    d1[d2, on=.(id), (cols) := mget(paste0("i.", cols))]
    

    As he notes, the original solution I provided below is a bad idea generally speaking. If ids appear multiple times or in a different order, it will do the wrong thing.

    d1[d1$id %in% d2$id, names(d2):=d2]

提交回复
热议问题