问题
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