Mina
Mina

Reputation: 307

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?

Upvotes: 1

Views: 175

Answers (1)

phiver
phiver

Reputation: 23608

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

Upvotes: 1

Related Questions