StudentOfScience
StudentOfScience

Reputation: 809

R: combining matrices by column name

matrix A is just a simple matrix with n rows and c columns matrix B is just a simple matrix with n rows and d columns

A and B thus have identical rows n, but different number of columns HOWEVER, some of the columns are identical (the name of the column and the values in that column)

I need to create a matrix C such that C has only those identical columns of A and B.

A and B have colnames() so that is how I though to do it but I am sure there is a faster way:

for (i in 1:ncol(A)){
    if(colnames(A)[i] == colnames(B)[i]){
        #do magic
    }

}

but this fails 2 places, A) obviously if the positions are different, so need "if (colnames(A)[i] is in colnames(B)) " and B) elements in B not in A are ignored; so overall this is a bad approach.

I used C = intersect(A, B) that did not work either; it gave me not what I wanted any advice?

thank you

Upvotes: 0

Views: 856

Answers (1)

Matthew Lundberg
Matthew Lundberg

Reputation: 42639

You need to call intersect on the names, and use the result for the index:

a <- matrix(1:15, 5)
b <- matrix(21:35, 5)
colnames(a) <- c('A', 'B', 'C')
colnames(b) <- c('A', 'C', 'D')

n <- intersect(colnames(a), colnames(b))
cbind(a[,n],b[,n])
##      A  C  A  C
## [1,] 1 11 21 26
## [2,] 2 12 22 27
## [3,] 3 13 23 28
## [4,] 4 14 24 29
## [5,] 5 15 25 30

I see that the question now says that the column values are the same, when the names agree. Thus, it is only necessary to index one of the matrices with the intersection of the names. Either will do:

a[,n]
##      A  C
## [1,] 1 11
## [2,] 2 12
## [3,] 3 13
## [4,] 4 14
## [5,] 5 15

Upvotes: 6

Related Questions