0

In R, I want to match and merge two matrices.

For example,

> A
     ID   a  b  c  d  e  f  g
  1  ex   3  8  7  6  9  8  4
  2  am   7  5  3  0  1  8  3
  3  ple  8  5  7  9  2  3  1

> B
    col1
  1  a
  2  c
  3  e
  4  f

Then, I want to match header of matrix A and 1st column of matrix B.

So I did

> C<-A[, c('ID', B[, 1])]

and the final result was like below.

> C
     ID   a  c  e  f
  1  ex   3  7  9  8
  2  am   7  3  1  8
  3  ple  8  7  2  3

However, if the matrix B has some values that are not in the matrix A like below,

> B
    col1
  1  a
  2  c
  3  e
  4  f
  5  x
  6  y

It says 'subscript out of bounds'.

How can I avoid this problem?

(How to extract duplicated columns only?)

tinmad
  • 7
  • 3
  • If you really are using matrices and not data.frames, please demonstrate it by making your question reproducible. Guidance here: http://stackoverflow.com/a/28481250/1191259 – Frank Aug 27 '15 at 18:07

1 Answers1

0

See if this works:

C<-A[, c('ID', colnames(A)[colnames(A) %in% B[,1]])]
C_Z_
  • 7,427
  • 5
  • 44
  • 81