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

Deadly 提交于 2019-12-08 05:44:19

问题


In R, 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.

Thanks a lot!

Avitus


回答1:


using %in%:

M[M[,1] %in% v,]

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


来源:https://stackoverflow.com/questions/16688024/in-r-extract-from-a-matrix-all-rows-indexed-by-the-components-of-a-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!