Home > Back-end >  Combine two data frames based on columes, keep all variables from each dataframe
Combine two data frames based on columes, keep all variables from each dataframe

Time:03-08

I have two data frames that need to combine together, an example shown below:

DF1
Name Symbole Weight Length
Apple Ap 0.5 0.5
Oranage Or 0.3 0.4
Banana Ba 0.2 0.6

DF2
Name Symbole Volumn
Apple Ap 0.52
Grape Gr 0.3
Banana Ba 0.35

Expected Output
Name Symbole Weight Length Volumn
Apple Ap 0.5 0.5 0.52
Oranage Or 0.3 0.4 NA
Banana Ba 0.2 0.6 0.35
Grape Gr NA NA 0.3

I tried: Res <- inner_join(DF1, DF2, by = c("Name", "Symbole")), but the output is only the common rows.

I alos tried: Res <- DF2 %>% right_join(DF1, by=c("Name","Symbole")), but it is adding the common rows into the dataframe.

Sorry that I use code as table in the post, since I think this may be better to explain my needs. Thanks all.

CodePudding user response:

You can use this code:

DF1 <- data.frame(Name = c("Apple", "Orange", "Banana"),
                  Symbole = c("Ap", "Or", "Ba"),
                  Weight = c(0.5, 0.3, 0.2),
                  Length = c(0.5, 0.4, 0.6))

DF2 <- data.frame(Name = c("Apple", "Grape", "Banana"),
                  Symbole = c("Ap", "Gr", "Ba"),
                  Volumn = c(0.52, 0.3, 0.35))

Res <- full_join(DF1, DF2, by = c("Name", "Symbole"))
Res

Output:

    Name Symbole Weight Length Volumn
1  Apple      Ap    0.5    0.5   0.52
2 Orange      Or    0.3    0.4     NA
3 Banana      Ba    0.2    0.6   0.35
4  Grape      Gr     NA     NA   0.30
  • Related