2

I have to combine two data-frames which look like this I want to take the common column among the data-frames and join them together. Rows in two data-frames will be completely different.

      a  b c 
row1  1  0 1      
row2  1  0 1

another dataframe

     d a c f
row3 1 0 1 1
row4 1 1 0 0 

I want the final dataset to look like this

        a c 
row1    1 1
row2    1 1
row3    0 1
row4    1 0

Here is the dput from two dataframes

dput(x1)
structure(list(d = c(1L, 1L), a = 0:1, c = c(1L, 0L), f = c(1L, 
0L)), .Names = c("d", "a", "c", "f"), row.names = c("row3", "row4"
), class = "data.frame")

dput(x2)
structure(list(a = c(1L, 1L), b = c(0L, 0L), c = c(1L, 1L)), .Names = c("a", 
"b", "c"), row.names = c("row1", "row2"), class = "data.frame")
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
dissw.geek9
  • 245
  • 1
  • 6
  • 11

2 Answers2

6

You could get the common names and then use row bind:

common <- intersect(names(x1), names(x2))
rbind(x1[,common], x2[,common])
     a c
row3 0 1
row4 1 0
row1 1 1
row2 1 1

EDIT: To match your expected output

 rbind(x2[,common], x1[,common])
     a c
row1 1 1
row2 1 1
row3 0 1
row4 1 0
user1609452
  • 4,406
  • 1
  • 15
  • 20
1

A very rudimentary version

> X <- merge(x1, x2, all=TRUE)
> X[, which(colSums(!is.na(X))==nrow(X))]
  a c
1 0 1
2 1 0
3 1 1
4 1 1
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138