Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to merge rows in R?

I have a data like this:

 name    A_1 B_1 A_2 B_2
"Jack"    20  NA  15  NA
"Jack"    NA  12  NA  30
"James"   22  NA  14  NA
"James"   NA  32  NA  20

I want to merge the rows like this:

name    A_1 B_1 A_2 B_2
"Jack"  20  12  15  30
"James" 22  32  14  20

How can I do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

First we group by the name, next fill all other columns that have missing data, first down, then up and last take the unique records.

library(dplyr)
library(tidyr)

df1 %>%
  group_by(name) %>% 
  fill(everything(), .direction = "downup") %>% 
  distinct()

# A tibble: 2 x 5
# Groups:   name [2]
  name    A_1   B_1   A_2   B_2
  <chr> <int> <int> <int> <int>
1 Jack     20    12    15    30
2 James    22    32    14    20
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading