Comparing rows between two matrices

后端 未结 2 1495
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-31 08:04

Is there a fast way of finding which rows in matrix A are present in matrix B? e.g.

m1 = matrix(c(1:6), ncol=2, byrow = T); m2 = matrix(c(1:4), ncol=2, byro         


        
相关标签:
2条回答
  • 2020-12-31 08:15

    I created this function which will return the original ID. For example you want to match matrix x to matrix y, it will return the match ID of y.

    rowiseMatch2 <- function(x,y){
      require(data.table)
      keycols <- colnames(x)
      x <- cbind(x, id=1:nrow(x))
      y <- cbind(y, id=1:nrow(y))
      m1 = data.table(x)
      setkeyv(m1, keycols)
      m2 = data.table(y)
      setkeyv(m2, keycols)
      m1id <- m1$id
      m2id <- m2$id
    
      m1$id <- NULL
      m2$id <- NULL
    
      m <- na.omit(m2[m1,which=TRUE])
      mo <- m2id[m][order(m1id)]
    
      if(length(mo) == nrow(x)){
        cat("Complete match!\n")
      }else{
        cat("Uncomplete match, match percentage is:", round(length(mo)/nrow(x), 4)*100, "%\n")
      }
      return(as.integer(mo))
    }
    
    0 讨论(0)
  • 2020-12-31 08:22

    A fast way for that size should be :

    require(data.table)
    M1 = setkey(data.table(m1))
    M2 = setkey(data.table(m2))
    na.omit(
        M2[M1,which=TRUE]
    )
    [1] 1 2
    
    0 讨论(0)
提交回复
热议问题