merge/combine columns with same name but incomplete data

后端 未结 7 958
臣服心动
臣服心动 2020-12-14 17:57

I have two data frames that have some columns with the same names and others with different names. The data frames look something like this:

df1
      ID hel         


        
7条回答
  •  伪装坚强ぢ
    2020-12-14 18:24

    Here's another data.table approach using binary merge

    library(data.table)
    setkey(setDT(df1), ID) ; setkey(setDT(df2), ID) # Converting to data.table objects and setting keys
    df1 <- df1[df2][, `:=`(i.hello = NULL, i.world = NULL)] # Full left join
    df1[df2[complete.cases(df2)], `:=`(hello = i.hello, world = i.world)][] # Joining only on non-missing values
    #    ID hello world football baseball hockey soccer
    # 1:  1     2     3       43        6      7      4
    # 2:  2     5     1       24       32      2      5
    # 3:  3    10     8        2       23      8     23
    # 4:  4     4    17        5       15      5     12
    # 5:  5     9     7       12       23      3     43
    

提交回复
热议问题