Search code examples
rmatrixuniquesubmatrix

In R, using `unique()` with extra conditions to extract submatrices: easy solution without plyr


In R, let M be the matrix

     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    1    3    3
[3,]    2    4    5
[4,]    6    7    8

I would like to select the submatrix m

     [,1] [,2] [,3]
[1,]    1    3    3
[2,]    2    4    5
[3,]    6    7    8

using unique on M[,1], specifying to keep the row with the maximal value in the second columnM. At the end, the algorithm should keep row [2,] from the set \{[1,], [2,]\}. Unfortunately unique() returns me a vector with actual values, and not row numbers, after elimination of duplicates.

Is there a way to get the asnwer without the package plyr? Thanks a lot, Avitus


Solution

  • Here's how:

    is.first.max <- function(x) seq_along(x) == which.max(x)
    
    M[as.logical(ave(M[, 2], M[, 1], FUN = is.first.max)), ]
    #      [,1] [,2] [,3]
    # [1,]    1    3    3
    # [2,]    2    4    5
    # [3,]    6    7    8