Removing matrix rows in a loop based on their index

In a loop, I define strings based on a test. I iteratively remove these rows from the original matrix (inM) using my index (idx):

inM <- inM[-idx,] 

Sometimes idx is empty, i.e. not a single line satisfies the test, therefore idx is of type integer (0). Removing idx from inM then gives an empty matrix, and not the same matrix. As a result, I got an empty matrix for the next iteration ...

Is there a one line solution to avoid this?

+4
source share
2 answers

You can avoid if with the ?setdiff function:

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

you can add a condition to your loop, for example:

 if (length(idx)==0) next 

like this, if there are no lines to delete, you go to the next iteration.

0
source

All Articles