1

I want to delete a row of matrix x indexed by vector k such as

x = matrix(1:10, 5, 2)
k = rep(1, 5)

# my attempt:
index = which(k == 0)
y = x[-index, ]
#      [,1] [,2]

Here, no rows meet my condition for dropping, k == 0, so index will return the empty vector, integer(0). Therefore, x[-index, ] will return a matrix with no lines instead of remaining itself.

I don't know how to handle this, please someone could help me on this?

Frank
  • 66,179
  • 8
  • 96
  • 180
  • Possible duplicate of [How do I delete rows in a data frame?](https://stackoverflow.com/questions/12328056/how-do-i-delete-rows-in-a-data-frame) – Nash Jul 11 '17 at 14:15
  • 1
    `y <- x[k != 0, ]`? – Axeman Jul 11 '17 at 14:18
  • 1
    `if (length(index)==0) {y <- x} else {y <- x[-index]}` – CPak Jul 11 '17 at 14:25
  • @Axeman, when `k` is not present, it gives the expected behavior, but when `k` is present, it gives different output than `y <- x[-index]`, at least for me... – CPak Jul 11 '17 at 14:45
  • Perhaps you can make an actually working example then instead of pseudo code. – Axeman Jul 11 '17 at 15:15
  • 1
    Yes, that's the risk when doing indexing like this. Better to stick with the raw condition (`k != 0`) than the possibly-zero-length vector of indices meeting it... – Frank Aug 16 '17 at 21:21

1 Answers1

0

The only complication could be k's size. Otherwise this should solve it: given x as:

  x=cbind(c(1,2,3,4,5,6),c(1,2,3,4,5,6))

and

  k=c(1,2,0,1,0,2)

then

  x[!k==0,]
user17784
  • 1
  • 1