选择满足条件的矩阵行 [英] Select rows of a matrix that meet a condition
问题描述
在R中具有矩阵:
one two three four
[1,] 1 6 11 16
[2,] 2 7 12 17
[3,] 3 8 11 18
[4,] 4 9 11 19
[5,] 5 10 15 20
我要提取其行的第三列为11的子矩阵.即:
I want to extract the submatrix whose rows have column three = 11. That is:
one two three four
[1,] 1 6 11 16
[3,] 3 8 11 18
[4,] 4 9 11 19
我想做到这一点而无需循环.我是R的新手,所以这可能很明显,但是 文档通常比较简洁.
I want to do this without looping. I am new to R so this is probably very obvious but the documentation is often somewhat terse.
推荐答案
如果使用as.data.frame()将矩阵转换为数据框,则此操作会更容易.在这种情况下,先前的答案(使用子集或m $ three)将起作用,否则将不起作用.
This is easier to do if you convert your matrix to a data frame using as.data.frame(). In that case the previous answers (using subset or m$three) will work, otherwise they will not.
要对矩阵执行操作,可以按名称定义列:
To perform the operation on a matrix, you can define a column by name:
m[m[, "three"] == 11,]
或按数字:
m[m[,3] == 11,]
请注意,如果只有一行匹配,则结果是整数矢量,而不是矩阵.
Note that if only one row matches, the result is an integer vector, not a matrix.
这篇关于选择满足条件的矩阵行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!