WAF
WAF

Reputation: 1151

Removing rows of a matrix in a loop based on their index

In a loop, I identify rows based on a test. I iteratively remove those rows from the original matrix (inM) using their index (idx):

 inM <- inM[-idx,]

Sometimes, idx is empty, i.e. no row satisfies the test, thus idx is of type integer(0). Removing idx from inM gives then a empty matrix rather than the same matrix. As a result, I got a empty matrix for the following iteration...

Is there a one-liner solution to avoid that?

Upvotes: 4

Views: 1008

Answers (2)

Nishanth
Nishanth

Reputation: 7130

You can avoid if by using ?setdiff function:

inM <- inM[setdiff(1:nrow(inM), idx), ]

Upvotes: 4

droopy
droopy

Reputation: 2818

you can add a condition in your loop for instance:

if (length(idx)==0)
  next

like this if there is no rows to delete you pass to the next iteration.

Upvotes: 0

Related Questions