[R] How to efficiently compare each row in a matrix with each row in another matrix?
arun
smartpink111 at yahoo.com
Tue Dec 11 00:17:42 CET 2012
HI Jonathan,
Thanks for the email.
I crosschecked my output with the output generated from the initial solution ("ind").
perhaps <- function(A,B){
nA <- nrow(A)
nB <- nrow(B)
C <-
kronecker(matrix(1,nrow=nA,ncol=1),B) >=
kronecker(A,matrix(1,nrow=nB,ncol=1))
matrix(rowSums(C) == ncol(A), nA, nB, byrow=TRUE)
}
Marius.5.0.Prev <- function(A,B) outer(rowMaxs(A),rowMins(B),'<') #Jonathan function
Marius.5.0 <- function(A,B) outer(rowMaxs(A),rowMins(B),'<=') #updated Jonathan function
Marius.4.0<-function(A,B){apply(B,1,function(x) colSums(x>=t(A)))==ncol(A)}
A <- rbind(matrix(1:4, ncol=2, byrow=TRUE), c(6, 2)) # (3, 2) matrix
B <- matrix(1:10, ncol=2) # (5, 2
ind <- apply(B, 1, function(b) apply(A, 1, function(a) all(a <= b))) #original function
ind
# [,1] [,2] [,3] [,4] [,5]
#[1,] TRUE TRUE TRUE TRUE TRUE
#[2,] FALSE FALSE TRUE TRUE TRUE
#[3,] FALSE FALSE FALSE FALSE FALSE
Marius.4.0(A,B)
# [,1] [,2] [,3] [,4] [,5]
#[1,] TRUE TRUE TRUE TRUE TRUE
#[2,] FALSE FALSE TRUE TRUE TRUE
#[3,] FALSE FALSE FALSE FALSE FALSE
perhaps(A,B)
# [,1] [,2] [,3] [,4] [,5]
#[1,] TRUE TRUE TRUE TRUE TRUE
#[2,] FALSE FALSE TRUE TRUE TRUE
#[3,] FALSE FALSE FALSE FALSE FALSE
Marius.5.0(A,B)
# [,1] [,2] [,3] [,4] [,5]
#[1,] FALSE TRUE TRUE TRUE TRUE
#[2,] FALSE FALSE FALSE TRUE TRUE
#[3,] FALSE FALSE FALSE FALSE FALSE
Marius.5.0.Prev(A,B)
# [,1] [,2] [,3] [,4] [,5]
#[1,] FALSE FALSE TRUE TRUE TRUE
#[2,] FALSE FALSE FALSE FALSE TRUE
#[3,] FALSE FALSE FALSE FALSE FALSE
A.K.
----- Original Message -----
From: "j2kennel at gmail.com" <j2kennel at gmail.com>
To: smartpink111 at yahoo.com
Cc:
Sent: Monday, December 10, 2012 5:39 PM
Subject: Re: How to efficiently compare each row in a matrix with each row in another matrix?
Hello Arun,
I saw your message. For some reason it doesn't let me post on the help site. It looks like I forgot an equal sign. It wasn't a problem with the random numbers because there was little chance a number would be repeated. It should be:
Marius.5.0 <- function(A,B) outer(rowMaxs(A),rowMins(B),'<=') #Jonathan's code
However, if you manually look at the example you provided, Marius.4.0 doesn't provide the correct answer either. There is one too many TRUE values (location [2,3]). The updated Marius.5.0 gives the correct result.
-Jonathan
More information about the R-help
mailing list