FRV
FRV

Reputation: 107

R - Get row numbers where two matrices have equal rows

I have to matrices and I want to no which rows are identical.

Lets say I have a matrix A which looks like this: A = matrix(1:12, 4, 3, byrow=T)

[,1] [,2] [,3]

[1,] 1 2 3

[2,] 4 5 6

[3,] 7 8 9

[4,] 10 11 12

a shorter matrix B: B <-matrix(c(0,2,2,7,8,9,4,5,6),3,3,byrow=T)

[,1] [,2] [,3]

[1,] 0 2 2

[2,] 7 8 9

[3,] 4 5 6

What I want is the row numbers of A when the rows are also present in B. In this example I would like to get: 2 and 3.

I tried to solve it with setkey but then I get only the rows but not the number of the row since the matrices are first sorted.

Upvotes: 2

Views: 1341

Answers (3)

DatamineR
DatamineR

Reputation: 9618

Alternatively you could use match_df from plyr:

match_df(data.frame(A),data.frame(B))
Matching on: X1, X2, X3
  X1 X2 X3
2  4  5  6
3  7  8  9

And to extract the numbers of the rows you could type as.numeric(rownames(match_df(data.frame(A),data.frame(B))))

Upvotes: 3

Marat Talipov
Marat Talipov

Reputation: 13304

The best way I know to do it is to convert matrix to string by rows:

sA <- apply(A,1,paste,collapse=' ')
sB <- apply(B,1,paste,collapse=' ')

which(sA %in% sB)
# [1] 2 3

Upvotes: 1

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

You can rbind the matrices together and use duplicated to figure out which rows are duplicated:

> duplicated(rbind(A, B), fromLast = TRUE)
[1] FALSE  TRUE  TRUE FALSE FALSE FALSE FALSE
> which(duplicated(rbind(A, B), fromLast = TRUE))
[1] 2 3

Upvotes: 1

Related Questions