0

I have 2 data.frames with the same colums, but different numbers of rows, and I want to replace some rows of df1 using an other the df2

library(dplyr)

df1 <- data.frame(ID = c(1,2,3,4,5,6),
                  Values1 = c(21,22,23,24,25,26),
                  Values2 = c(435,33,45,100, 120,12))
df2 <- data.frame(ID = c(4,5),
                  Values1 = c(50,75),
                  Values2 = c(544, 676))


df1
  ID Values1 Values2
1  1      21     435
2  2      22      33
3  3      23      45
4  4      24     100
5  5      25     120
6  6      26      12

df2
  ID Values1 Values2
1  4      50     544
2  5      75     676

I want to eliminate all the data of ID 4 and 5 in df1 and replace with the values of df2, I made it with a filter and then rbind

filter(df1, !ID %in% df2$ID ) %>% rbind(., df2) %>% arrange(ID)

  ID Values1 Values2
1  1      21     435
2  2      22      33
3  3      23      45
4  4      50     544
5  5      75     676
6  6      26      12

but I think it could be better way to do it, any advise ?

Thanks !!!

abraham
  • 661
  • 8
  • 14

0 Answers0