Updating rows of a data.frame with the rows of another data.frame

64 Views Asked by At

I want to update the rows of data.frame df1 with the rows of data.frame df2. Any hint?

df1 <-
  data.frame(
    "V1" = LETTERS[1:4]
  , "V2" = 1:4
  , "V3" = 7:10
  )

df1
  V1 V2 V3
1  A  1  7
2  B  2  8
3  C  3  9
4  D  4 10


df2 <-
  data.frame(
      "V1" = c("A","D")
    , "V2" = c(5, 7)
    , "V3" = c(12, 15)
  )


df2
  V1 V2 V3
1  A  5 12
2  D  7 15

Required Output

  V1 V2 V3
1  A  5 12
2  B  2  8
3  C  3  9
4  D  7 15
2

There are 2 best solutions below

0
Yuriy Saraykin On BEST ANSWER

use dplyr 1.0.0

rows_update(df1, df2)

Matching, by = "V1"
  V1 V2 V3
1  A  5 12
2  B  2  8
3  C  3  9
4  D  7 15
0
Duck On

Try this:

df1[df1$V1 %in% df2$V1,c('V2','V3')] <- df2[df2$V1 %in% df1$V1,c('V2','V3')]

  V1 V2 V3
1  A  5 12
2  B  2  8
3  C  3  9
4  D  7 15