合并两个数据框,保留所有列 [英] Combining two dataframes keeping all columns
问题描述
我想做的是合并2个数据帧,保留所有列(在下面的示例中未完成),并在数据帧中有不常见变量的地方输入零.
What I would like to do is combine 2 dataframes, keeping all columns (which is not done in the example below) and input zeros where there are gaps in the dataframe from uncommon variables.
这似乎是plyr或dplyr主题.但是,plyr中的完全联接不会保留所有列,而左联接或右联接不能保留我想要的所有行.查看dplyr速查表( http://www .rstudio.com/wp-content/uploads/2015/02/data-wrangling-cheatsheet.pdf ),full_join似乎是我需要的功能,但R成功加载包后无法识别此功能.
This seems like a plyr or dplyr theme. However, a full join in plyr does not keep all of the columns, whilst a left or a right join does not keep all the rows I desire. Looking at the dplyr cheatsheet (http://www.rstudio.com/wp-content/uploads/2015/02/data-wrangling-cheatsheet.pdf), a full_join seems to be the function I need, but R does not recognise this function after succesfully loading the package.
例如:
col1 <- c("ab","bc","cd","de")
col2 <- c(1,2,3,4)
df1 <- as.data.frame(cbind(col1,col2))
col1 <- c("ab","ef","fg","gh")
col3 <- c(5,6,7,8)
df2 <- as.data.frame(cbind(col1,col3))
library(plyr)
Example <- join(df1,df2,by = "col1", type = "full") #Does not keep col3
library(dplyr)
Example <- full_join(df1,df2,by = "col1") #Function not recognised
我想要输出...
col1 col2 col3
ab 1 5
bc 2 0
cd 3 0
de 4 0
ef 0 6
fg 0 7
gh 0 8
推荐答案
在上述大卫·阿伦伯格(David Arenberg)发表评论之后...
Following David Arenberg's comment above...
Example <- merge(df1, df2, by = "col1", all = TRUE)
这篇关于合并两个数据框,保留所有列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!