'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?



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 phiver