R:如果某行中的某个元素满足某些特征,如何删除行? [英] R: How can I delete rows if an element in a row satisfies certain characteristic?
问题描述
我正在尝试找出一种删除矩阵行的方法,如果该行中的某个单元格满足某个特征。例如:
I am trying to figure out a way to delete rows of matrix if a cell in that row satisfies a certain characteristic. For example:
> mm <- matrix(c(1,2,3,2,3,4,1,2,3,4),5,2)
> mm
[,1] [,2]
[1,] 1 4
[2,] 2 1
[3,] 3 2
[4,] 2 3
[5,] 3 4
如果第1个,我想删除行该行中的列元素为2。最后,我要这样:
I want to delete rows if the 1st column element in that row is 2. At the end I want this:
[,1] [,2]
[1,] 1 4
[2,] 3 2
[3,] 3 4
我该怎么做?
如果不是删除第一个列元素为2的所有行,而是更通用的方法呢?删除谁的第一列元素对应于列表中包含的一组数字的行?例如,
And what about a more general method if instead of deleting all rows who's first column element is 2, I needed to delete rows who's first column element corresponds to a set of numbers that are contained in a list? For example
delete_list <- c(2,3)
做到这一点的最佳方法是什么?
What is the best way to do this?
请先谢谢您。
推荐答案
只需使用
mm2 <- mm[mm[,1]!=2,]
这有效是因为
mm[,1] != 2
返回
[1] TRUE FALSE TRUE FALSE TRUE
实际上,您是使用此布尔数组来选择要选择的行。
and essentially you are using this boolean array to choose which rows to pick.
这篇关于R:如果某行中的某个元素满足某些特征,如何删除行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!