Search code examples
rmatrixsubmatrix

Extract from a matrix all rows indexed by the components of a vector


Let M be the matrix:

     [,1] [,2]
[1,]    1    9
[2,]    3   12
[3,]    6    4
[4,]    7    2

I would like to extract all rows with entries equal to the components of the vector v <- c(3,6,1) from column [,1] in M producing the submatrix m:

         [,1] [,2]
    [1,]    1    9
    [2,]    3   12
    [3,]    6    4

I tried

m <- M[which(M[,1] == v), ]

Obtaining the error message longer object length is not a multiple of shorter object length. Using the transpose t(v) of v does not help.


Solution

  • using %in%:

    M[M[,1] %in% v,]
    
         [,1] [,2]
    [1,]    1    9
    [2,]    3   12
    [3,]    6    4