In R, match function for rows or columns of matrix

前端 未结 5 608
走了就别回头了
走了就别回头了 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
    

提交回复
热议问题