Skip to content
Prev 327643 / 398502 Next

Intersecting two matrices

I haven't looked at the size-time relationship, but im2 (below) is faster than your
function on at least one example:

intersectMat <- function(mat1, mat2)
{
    #mat1 and mat2 are both deduplicated
    nr1 <- nrow(mat1)
    nr2 <- nrow(mat2)
    mat2[duplicated(rbind(mat1, mat2))[(nr1 + 1):(nr1 + nr2)], , drop=FALSE]
}

im2 <- function(mat1, mat2)
{
    stopifnot(ncol(mat1)==2, ncol(mat1)==ncol(mat2))
    toChar <- function(twoColMat) paste(sep="\1", twoColMat[,1], twoColMat[,2])
    mat1[match(toChar(mat2), toChar(mat1), nomatch=0), , drop=FALSE]
}
user  system elapsed 
 430.37    1.96  433.98
user  system elapsed 
  27.89    0.20   28.13
[1] TRUE
[1] 5000000       2

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com