Home > Net >  Merge partial rows while keeping the rest
Merge partial rows while keeping the rest

Time:12-10

I would like to merge some rows while keeping the rest of the rows and the order of columns.

df1 <- data.frame(by1=c(1,3,5,7,9),
                 by2=c(6:10),
                 x=c("a",NA_character_,NA_character_,NA_character_,"e"),
                 y=c("q","w","e","r","t"),stringsAsFactors = F)
df1
  by1 by2    x y
1   1   6    a q
2   3   7 <NA> w
3   5   8 <NA> e
4   7   9 <NA> r
5   9  10    e t


df2 <- data.frame(by1=c(3,5),x=c("b","c"),stringsAsFactors = F)
df2
  by1 x
1   3 b
2   5 c

Expected output:

expected <- data.frame(by1=c(1,3,5,7,9),
                       by2=c(6:10),
                       x=c("a","b","c",NA_character_,"e"),
                       y=c("q","w","e","r","t"),stringsAsFactors = F )
expected
  by1 by2    x y
1   1   6    a q
2   3   7    b w
3   5   8    c e
4   7   9 <NA> r
5   9  10    e t

I can get the expected output by using the following code. However, it is not clean:

df1%>%
  merge(df2%>%rename(x2=x),by="by1",all.x=T)%>%
  mutate(x=coalesce(x,x2))%>%
  select(-x2)

CodePudding user response:

Use rows_update

library(dplyr)
rows_update(df1, df2)

-output

  by1 by2    x y
1   1   6    a q
2   3   7    b w
3   5   8    c e
4   7   9 <NA> r
5   9  10    e t
  • Related