简体   繁体   中英

Matching, merging, finding duplicated value in R

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?)

查看是否可行:

C<-A[, c('ID', colnames(A)[colnames(A) %in% B[,1]])]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM