简体   繁体   English

如何删除矩阵中的行

[英]How to remove rows in a matrix

I am faking a matrix as follows. 我伪造如下矩阵。

a = rep(1:4, each=2)
b = rep(0:1, times=4)
m = cbind(a, b)
m
a b
[1,] 1 0
[2,] 1 1
[3,] 2 0
[4,] 2 1
[5,] 3 0
[6,] 3 1
[7,] 4 0
[8,] 4 1

I need to remove any rows where a==4 and b==0 . 我需要删除a==4b==0所有行。 I know how to select such rows: 我知道如何选择这样的行:

m[m[,1]==4 & m[,2]==0,]
a b 
4 0 

But I have no idea how to remove them. 但是我不知道如何删除它们。 I know that I can do m[-7,] in this particular case. 我知道在这种情况下我可以做m[-7,] But image that this is a huge matrix and I cannot visually inspect which rows meet the condition as a==4 and b==0 . 但是,这是一个巨大的矩阵,我无法直观地检查哪些行满足a==4b==0 I also tried this: 我也试过这个:

count=1:8
m.count = cbind(m, count)
m.count[m.count[,1]==4 & m.count[,2]==0,]
a     b count 
4     0     7 

So this will automatically tells me which rows meet the condition and then I can use the index c=count[3] (if only one row) or c=count[,3] (if more than one row) and try m[-c,] to get the right results. 因此,这将自动告诉我哪些行满足条件,然后可以使用索引c=count[3] (如果只有一行)或c=count[,3] (如果有多于一行)并尝试m[-c,]以获得正确的结果。

But this solution is too lengthy. 但是这个解决方案太冗长了。 Does anyone know a easy way to solve the problem? 有谁知道解决问题的简便方法? I am expected to use "-" in some smart ways to do it. 我应该以一些聪明的方式使用"-"来做到这一点。

Just invert your condition for selecting rows: 只需反转选择行的条件即可:

m[! (m[, 1] == 4 & m[, 2] == 0), ]

Or indeed (as per De Morgan ): 或确实如此(根据De Morgan ):

m[m[, 1] != 4 | m[, 2] != 0, ]

I think you just need ?which 我想你只需要?which

m <- m[-which(m[,1] == 4 & m[,2] == 0),]

Testing: 测试:

# Konrad's !

> system.time(rep(m[! (m[, 1] == 4 & m[, 2] == 0), ],10000000))
   user  system elapsed 
  0.264   0.094   0.357 

# BB's which
> system.time(rep(m[-which(m[,1] == 4 & m[,2] == 0),],10000000))
   user  system elapsed 
  0.244   0.109   0.354 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM