如果存在一个具有不同级别的公因子,则可以合并数据帧,但结果将显示所有级别的dplyr。我们可以使用left_join函数来连接两个数据帧,但是如果它们不相同,则第一个数据帧的大小必须大于第二个数据帧的大小。
请看以下数据帧-
> Class<-c("Statistics","Maths","Chemistry","Physics","Economics","Political Science", + "Geography") > df1<-data.frame(Class) > df1 Class 1 Statistics 2 Maths 3 Chemistry 4 Physics 5 Economics 6 Political Science 7 Geography > Subject<-c("Maths","Chemistry","Physics","Economics","Political Science", + "Geography") > Age<-c(18,21,22,25,21,23) > df2<-data.frame(Subject,Age) > df2 Subject Age 1 Maths 18 2 Chemistry 21 3 Physics 22 4 Economics 25 5 Political Science 21 6 Geography 23
在这两个数据框中,因子类和主题的级别相同,因此我们可以使用它们来合并数据框。
加载dplyr软件包-
> library(dplyr)
连接两个数据帧-
> left_join(df1,df2, by = c("Class" = "Subject")) Class Age 1 Statistics NA 2 Maths 18 3 Chemistry 21 4 Physics 22 5 Economics 25 6 Political Science 21 7 Geography 23 Warning message: Column `Class`/`Subject` joining factors with different levels, coercing to character vector
它正在显示警告,但这不是问题,因为此警告只是告诉我们两个数据帧中存在不同级别的因素。