Home > OS >  (R) how to merge rows and retain non-duplicate rows
(R) how to merge rows and retain non-duplicate rows

Time:10-13

I have data with columns like this

  Date    Col1    Col2    Col3    Col4
  4        2       3       NA      NA 
  4        NA      NA      1       6
  5        NA      1       NA      NA 
  9        2       NA      1       6

Some of the rows are duplicated where when they are merged then they fit together perfectly and there are no missing values. I've used merge() but that removes any rows that don't have a duplicate, where I would like to retain these rows. I'm trying to get an output like this:

  Date    Col1    Col2    Col3    Col4
  4        2       3       1       6 
  5        NA      1       NA      NA 
  9        2       NA      1       6

Any help is appreciated!

CodePudding user response:

in base R you could do:

aggregate(.~Date, df, function(x)na.omit(x)[1], na.action = identity)

  Date Col1 Col2 Col3 Col4
1    4    2    3    1    6
2    5   NA    1   NA   NA
3    9    2   NA    1    6
  • Related