Lei
Lei

Reputation: 103

R: Merge two data frames by common columns

I have two data.frames, "x" and "y". "x" and "y" have different numbers of columns. As the following:

x
  A1 A3 A5 A6
1  a  b  b  a

y
   A1 A2 A3 A4 A5 A6 A7
1   9 10 11  9 10 10 10
2   0  6  2  2  8  1  4
3   0  4  0  1  0  0  0
4  12 12 12 12 12 12 11
5  11 11  9 12 12 11 11
6   0  0  0  0  0  1  0

I want to create a new data.frame, with only common columns to the two data.frames. And the content of this new data.frame only coming from "y". The final data.frame should look like this:

  A1 A3 A4 A6
1  9 11  9 10
2  0  2  2  1
3  0  0  1  0
4 12 12 12 12
5 11  9 12 11
6  0  0  0  1

These are examples. In fact, there are hundreds of columns in my real data.frames. Does anyone know how to do it?

Upvotes: 4

Views: 357

Answers (2)

user227710
user227710

Reputation: 3194

Try this:

 y[,colnames(y) %in%colnames(x)]
  A1 A3 A5 A6
1  9 11 10 10
2  0  2  8  1
3  0  0  0  0
4 12 12 12 12
5 11  9 12 11
6  0  0  0  1

Upvotes: 8

josliber
josliber

Reputation: 44320

You can index y by the column names that x and y have in common:

y[,intersect(names(x), names(y))]
#   A1 A3 A5 A6
# 1  9 11 10 10
# 2  0  2  8  1
# 3  0  0  0  0
# 4 12 12 12 12
# 5 11  9 12 11
# 6  0  0  0  1

Upvotes: 6

Related Questions