Search code examples
rdplyrrbind

Make two dataframes into the same form in R


Say I have a dataframe as:

DF1

ID   Name  Fruit      Berry  Price
01   Jim   Apple      No     .69
02   Rick  Blueberry  Yes    1.50

And another:

DF2

Name    ID   Price   Berry   Fruit  
Hannah  03   1.20    No      Apple  
Allie   04   .40             Canteloupe 

So the goal is simple, I just want to rbind these together. But the columns aren't aligned. The real dataframe has like 30 vars, so how could I put these together and reorder the vars accordingly.

Final df goal:

ID   Name   Fruit      Berry  Price
01   Jim    Apple      No     .69
02   Rick   Blueberry  Yes    1.50
03   Hannah Apple      No     1.20       
04   Allie  Canteloupe        .40

Solution

  • We can use bind_rows which automatically rearranges the columns of second based on the first dataset

    library(dplyr)
    bind_rows(DF1, DF2)
    

    -output

    #  ID   Name      Fruit Berry Price
    #1  1    Jim      Apple    No  0.69
    #2  2   Rick  Blueberry   Yes  1.50
    #3  3 Hannah      Apple    No  1.20
    #4  4  Allie Canteloupe  <NA>  0.40
    

    data

    DF1 <- structure(list(ID = 1:2, Name = c("Jim", "Rick"), Fruit = c("Apple", 
    "Blueberry"), Berry = c("No", "Yes"), Price = c(0.69, 1.5)), 
    class = "data.frame", row.names = c(NA, 
    -2L))
    
    
    DF2 <- structure(list(Name = c("Hannah", "Allie"), ID = 3:4, Price = c(1.2, 
    0.4), Berry = c("No", NA), Fruit = c("Apple", "Canteloupe")), 
    class = "data.frame", row.names = c(NA, 
    -2L))