4

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?

2 Answers 2

8

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
Sign up to request clarification or add additional context in comments.

Comments

6

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.