left_join two data frames and overwrite

后端 未结 2 1156
难免孤独
难免孤独 2021-01-04 12:50

I\'d like to merge two data frames where df2 overwrites any values that are NA or present in df1. Merge data frames and overwrite val

2条回答
  •  梦毁少年i
    2021-01-04 13:42

    I think what you want is to keep the values of df2 and only add the ones in df1 that are not present in df2 which is what anti_join does:

    "anti_join return all rows from x where there are not matching values in y, keeping just columns from x."

    My solution:

    df3 <- anti_join(df1, df2, by = "y") %>% bind_rows(df2)
    
    Warning messages:
    1: In anti_join_impl(x, y, by$x, by$y) :
      joining factors with different levels, coercing to character vector
    2: In rbind_all(x, .id) : Unequal factor levels: coercing to character
    
    > df3
    Source: local data frame [4 x 2]
    
          y    x1
      (chr) (dbl)
    1     D     4
    2     A     5
    3     B     6
    4     C     7
    

    this line gives the desired output (in a different order) but, you should pay attention to the warning message, when working with your dataset be sure to read y as a character variable.

提交回复
热议问题