在R中将两个数据帧制作成相同的形式

Make two dataframes into the same form in R

假设我有一个数据框:

DF1

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

还有一个:

DF2

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

所以目标很简单,我只是想把这些rbind在一起。但是列没有对齐。真正的数据框有大约 30 个变量,所以我如何将它们放在一起并相应地重新排序变量。

最终目标:

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

我们可以使用 bind_rows 它会根据第一个数据集自动重新排列第二个列

library(dplyr)
bind_rows(DF1, DF2)

-输出

#  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

数据

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))