In R, match function for rows or columns of matrix

You could do that without using any functions:

Suppose adj1 is the 3*3 matrix with both colnames and row.names being c('V1','V2','V3') and vec1 is the order you want your matrix to be transformed into:

vec1 <- c('V2','V3','V1')

You could simply using the following code:

adj1[vec1,vec1]

Which will do you the magic.

Cheers!


You can use asplit to create a list which can be used by match. But the manual says lists are converted to character vectors and Matching for lists is potentially very slow and best avoided except in simple cases.

match(asplit(x, 1), asplit(y, 1))
#[1] NA  1  2

So maybe using interaction or paste is an option.

match(interaction(data.frame(x)), interaction(data.frame(y)))
#[1] NA  1  2

match(apply(x, 1, paste, collapse =" "), apply(y, 1, paste, collapse =" "))
#[1] NA  1  2

Data:

(x <- matrix(1:9, 3))
#     [,1] [,2] [,3]
#[1,]    1    4    7
#[2,]    2    5    8
#[3,]    3    6    9

(y <- matrix(2:10, 3))
#     [,1] [,2] [,3]
#[1,]    2    5    8
#[2,]    3    6    9
#[3,]    4    7   10

The function row.match in the package prodlim allows you to identify the rows in one matrix that are also found (identical) in another matrix. Very convenient and easy to use.

library(prodlim)
row.match(x,y)

match will work on lists of atomic vectors. So to match rows of one matrix to another, you could do:

match(data.frame(t(x)), data.frame(t(y)))

t transposes the rows into columns, then data.frame creates a list of the columns in the transposed matrix.

Tags:

R