matrix %in% matrix

后端 未结 5 917
北恋
北恋 2020-12-08 23:24

Suppose I have two matrices, each with two columns and differing numbers of row. I want to check and see which pairs of one matrix are in the other matrix. If these were one

5条回答
  •  情书的邮戳
    2020-12-08 23:31

    Andrie's solution is perfectly fine. But if you have big matrices, you might want to try something else, based on recursion. If you work columnwise, you can cut down on the calculation time by excluding everything that doesn't match at the first position:

    fastercheck <- function(x,matrix){
      nc <- ncol(matrix)
      rec.check <- function(r,i,id){
        id[id] <- matrix[id,i] %in% r[i]
        if(i

    The comparison :

    > set.seed(100)
    > x <- matrix(runif(1e6),ncol=10)
    > a <- matrix(runif(300),ncol=10)
    > a[c(3,7,9,15),] <- x[c(1000,48213,867,20459),]
    > system.time(res1 <- a %inm% x)
       user  system elapsed 
      31.16    0.14   31.50 
    > system.time(res2 <- fastercheck(a,x))
       user  system elapsed 
       0.37    0.00    0.38 
    > identical(res1, res2)
    [1] TRUE
    > which(res2)
    [1]  3  7  9 15
    

    EDIT:

    I checked the accepted answer just for fun. Performs better than the double apply ( as you get rid of the inner loop), but recursion still rules! ;-)

    > system.time(apply(a, 1, paste, collapse="$$") %in% 
     + apply(x, 1, paste, collapse="$$"))
       user  system elapsed 
       6.40    0.01    6.41 
    

提交回复
热议问题