Mark
Mark

Reputation: 1769

Indices of matching of rows between matrices

Let n be a positive integer. We have a matrix B that has n columns, whose entries are integers between 1 and n. The aim is to match the rows of B with the rows of permutations(n), memorizing the indices in a vector v.

For example, let us consider the following. If

permutations(3)=
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    1    3    2
[3,]    2    1    3
[4,]    2    3    1
[5,]    3    1    2
[6,]    3    2    1

and

B=
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    1    2    3
[3,]    3    1    2
[4,]    2    3    1
[5,]    3    1    2

Then the vector v is

1 1 5 4 5

because the first two rows of B are equal to the row number 1 of permutations(3), the third row of B is the row number 5 of permutations(3), and so on.

I tried to apply the command

 row.match

but the latter returns the error:

Error in do.call("paste", c(x[, , drop = FALSE], sep = "\r")) : 
second argument must be a list

Upvotes: 0

Views: 136

Answers (2)

AntoniosK
AntoniosK

Reputation: 16121

One possible way is to turn your matrices into dataframes and join them:

A = read.table(text = "
1    2    3
1    3    2
2    1    3
2    3    1
3    1    2
3    2    1
")

B = read.table(text = "
1    2    3
1    2    3
3    1    2
2    3    1
3    1    2
")

library(dplyr)

A %>%
  mutate(row_id = row_number()) %>%
  right_join(B) %>%
  pull(row_id)

# [1] 1 1 5 4 5

Upvotes: 2

Sotos
Sotos

Reputation: 51592

One way is to use match,

match(do.call(paste, data.frame(B)), do.call(paste, data.frame(m1)))
#[1] 1 1 5 4 5

Upvotes: 4

Related Questions