I have 2 data frames with different number of columns each. Some of the columns are common between the 2 data frames. How can i rbind only the common columns of the two data
made my own function for my personal package: (this works also for more than 2 dataframes)
function:
fast.rbind <- function(...,method=c("fill","common"),value=NA){
if("fill"==method[1]) {
fun1 <- function(x,y,value=NA){
x[setdiff(colnames(y),colnames(x))] <- value
y[setdiff(colnames(x),colnames(y))] <- value
return(rbind(x,y))
}
}
if("common"==method[1]) {
fun1 <- function(x,y,value=NULL){
common_cols <- intersect(colnames(x), colnames(y))
return(rbind(x[, common_cols,drop=F],y[, common_cols,drop=F]))
}
}
return(Reduce(function(x,y){fun1(x=x,y=y,value=value)},list(...)))
}
call + example data:
df1 <- mtcars[1:5,1:4]
df2 <- mtcars[6:10,2:5]
df3 <- mtcars[11:15,4:7]
fast.rbind(df1,df2,df3,method="common")
fast.rbind(df1,df2,df3,value="yourDesiredFill")