matrix %in% matrix

后端 未结 5 916
北恋
北恋 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:29

    Recreate your data:

    a <- matrix(c(1, 2, 4, 9, 1, 6, 7, 7), ncol=2, byrow=TRUE)
    x <- matrix(c(1, 6, 2, 7, 3, 8, 4, 9, 5, 10), ncol=2, byrow=TRUE)
    

    Define a function %inm% that is a matrix analogue to %in%:

    `%inm%` <- function(x, matrix){
      test <- apply(matrix, 1, `==`, x)
      any(apply(test, 2, all))
    }
    

    Apply this to your data:

    apply(a, 1, `%inm%`, x)
    [1] FALSE  TRUE  TRUE FALSE
    

    To compare a single row:

    a[1, ] %inm% x
    [1] FALSE
    
    a[2, ] %inm% x
    [1] TRUE
    

提交回复
热议问题