选择矩阵中满足条件的行 [英] Select rows of a matrix that meet a condition
问题描述
在带有矩阵的 R 中:
In R with a matrix:
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屋!