R: Updating a data frame with another data frame

后端 未结 4 1133
别那么骄傲
别那么骄傲 2020-12-18 12:51

Let\'s say our initial data frame looks like this:

df1 = data.frame(Index=c(1:6),A=c(1:6),B=c(1,2,3,NA,NA,NA),C=c(1,2,3,NA,NA,NA))

> df1
  Index A  B  C
         


        
4条回答
  •  庸人自扰
    2020-12-18 13:02

    We can use join from data.table. Convert the 'data.frame' to 'data.table' (setDT(df1), join on with 'df1' using "Index" and assign (:=), the values in 'B' and 'C' with 'i.B' and 'i.C'.

    library(data.table)
    setDT(df1)[df2, c('B', 'C') := .(i.B, i.C), on = "Index"]
    df1
    #   Index A B C
    #1:     1 1 1 1
    #2:     2 2 2 2
    #3:     3 3 3 3
    #4:     4 4 4 5
    #5:     5 5 4 5
    #6:     6 6 4 5
    

提交回复
热议问题