WAF
WAF

Reputation: 1151

Find indices of rows from matrix A in matrix B

Let's consider two matrices A and B. A is a subset of B. How to find the index of each row of A in matrix B? Here is a reproductible example:

set.seed(30)
B <- matrix(rnorm(n =30,mean = 0), ncol=3)
A <- subset(B, B[,1] > 1)

The goal is to find the indices idx which in this case gives row 4 and 5.

Upvotes: 4

Views: 182

Answers (4)

Simon O&#39;Hanlon
Simon O&#39;Hanlon

Reputation: 59970

This takes a slightly different approach and relies on the fact that a matrix is a vector, it won't work if you have data.frames:

which( B %in% A , arr.ind=TRUE )[1:nrow(A)]
#[1] 4 5

And if you had really big matrices and wanted to be a bit more efficient you could use %in% on a subset like so:

which( B[1:nrow(B)] %in% A[1:nrow(A)] , arr.ind=TRUE )

But I don't expect this would make too much of a difference except in really big matrices.

If you had your data as data.frames you could do the same thing by passing just the first column to which:

A <- data.frame(A)
B <- data.frame(B)
which( B$X1 %in% A$X1 )
#[1] 4 5

Upvotes: 0

Aaron - mostly inactive
Aaron - mostly inactive

Reputation: 37754

> match(apply(A, 1, paste, collapse="\b"), apply(B, 1, paste, collapse="\b"))
[1] 4 5

Upvotes: 0

Maxim.K
Maxim.K

Reputation: 4180

Alternatively, you could do this:

transform(A, idx = 1 * duplicated(rbind(A, B))[-seq_len(nrow(A))])

A nice solution without apply, originally by @Arun.

Upvotes: 0

Ricardo Saporta
Ricardo Saporta

Reputation: 55350

Nested apply loops should do it.

apply(A, 1, function(a)
   which(apply(B, 1, function(b) all(b==a)))
 )

# [1] 4 5

Or alternatively, using colSums

apply(A, 1, function(a) 
    which(colSums(t(B) == a) == ncol(B)))
# [1] 4 5

Upvotes: 3

Related Questions