Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Merge two data frames by common columns

Tags:

merge

r

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?

like image 772
Lei Avatar asked Dec 08 '22 03:12

Lei


2 Answers

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
like image 124
user227710 Avatar answered Dec 10 '22 17:12

user227710


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
like image 36
josliber Avatar answered Dec 10 '22 15:12

josliber