문제

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. 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. But image that this is a huge matrix and I cannot visually inspect which rows meet the condition as a==4 and b==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.

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):

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

다른 팁

I think you just need ?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 ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top