[R] How to efficiently compare each row in a matrix with each row in another matrix?
Marius Hofert
marius.hofert at math.ethz.ch
Sat Dec 8 12:28:54 CET 2012
Dear expeRts,
I have two matrices A and B. They have the same number of columns but possibly different number of rows. I would like to compare each row of A with each row of B and check whether all entries in a row of A are less than or equal to all entries in a row of B. Here is a minimal working example:
A <- rbind(matrix(1:4, ncol=2, byrow=TRUE), c(6, 2)) # (3, 2) matrix
B <- matrix(1:10, ncol=2) # (5, 2) matrix
( ind <- apply(B, 1, function(b) apply(A, 1, function(a) all(a <= b))) ) # (3, 5) = (nrow(A), nrow(B)) matrix
The question is: How can this be implemented more efficiently in R, that is, in a faster way?
Thanks & cheers,
Marius
More information about the R-help
mailing list