如何合并 2 个相似的数据框,但有一个更重要?
例如:
数据框 1
Date Col1 Col2
jan 2 1
feb 4 2
march 6 3
april 8 NA
数据框 2
Date Col2 Col3
jan 9 10
feb 8 20
march 7 30
april 6 40
按日期合并这些,数据框 1 优先,但数据框 2 填充空白
数据框合并
Date Col1 Col2 Col3
jan 2 1 10
feb 4 2 20
march 6 3 30
april 8 6 40
编辑 - 解决方案
commonNames <- names(df1)[which(colnames(df1) %in% colnames(df2))]
commonNames <- commonNames[commonNames != "key"]
dfmerge<- merge(df1,df2,by="key",all=T)
for(i in commonNames){
left <- paste(i, ".x", sep="")
right <- paste(i, ".y", sep="")
dfmerge[is.na(dfmerge[left]),left] <- dfmerge[is.na(dfmerge[left]),right]
dfmerge[right]<- NULL
colnames(dfmerge)[colnames(dfmerge) == left] <- i
}