In R, match function for rows or columns of matrix

前端 未结 5 580
走了就别回头了
走了就别回头了 2020-12-31 23:06

The value matching function in R is very useful. But from my understanding, it does not sufficiently support two or high dimensional inputs.

For examp

相关标签:
5条回答
  • 2020-12-31 23:44

    You can use asplit to create a list which can be used by match. But the manual says lists are converted to character vectors and Matching for lists is potentially very slow and best avoided except in simple cases.

    match(asplit(x, 1), asplit(y, 1))
    #[1] NA  1  2
    

    So maybe using interaction or paste is an option.

    match(interaction(data.frame(x)), interaction(data.frame(y)))
    #[1] NA  1  2
    
    match(apply(x, 1, paste, collapse =" "), apply(y, 1, paste, collapse =" "))
    #[1] NA  1  2
    

    Data:

    (x <- matrix(1:9, 3))
    #     [,1] [,2] [,3]
    #[1,]    1    4    7
    #[2,]    2    5    8
    #[3,]    3    6    9
    
    (y <- matrix(2:10, 3))
    #     [,1] [,2] [,3]
    #[1,]    2    5    8
    #[2,]    3    6    9
    #[3,]    4    7   10
    
    0 讨论(0)
  • 2020-12-31 23:49

    The function row.match in the package prodlim allows you to identify the rows in one matrix that are also found (identical) in another matrix. Very convenient and easy to use.

    library(prodlim)
    row.match(x,y)
    
    0 讨论(0)
  • 2020-12-31 23:49

    You could use apply:

    z <- apply(x, 1, function(a) apply(y, 1, function(b) all(a==b)))
    

    This will generate a matrix with nrow(x) rows and nrow(y) columns, whose entries mark the indices where there is a match.

    0 讨论(0)
  • 2020-12-31 23:56

    You could do that without using any functions:

    Suppose adj1 is the 3*3 matrix with both colnames and row.names being c('V1','V2','V3') and vec1 is the order you want your matrix to be transformed into:

    vec1 <- c('V2','V3','V1')
    

    You could simply using the following code:

    adj1[vec1,vec1]
    

    Which will do you the magic.

    Cheers!

    0 讨论(0)
  • 2021-01-01 00:08

    match will work on lists of atomic vectors. So to match rows of one matrix to another, you could do:

    match(data.frame(t(x)), data.frame(t(y)))
    

    t transposes the rows into columns, then data.frame creates a list of the columns in the transposed matrix.

    0 讨论(0)
提交回复
热议问题