Jagoda
Jagoda

Reputation: 424

Avoiding 'while' loop in R

I'm wondering, whether it is possible to omit 'while' loop in this part of R code?

while (matrix[i] != -1){
        i = i+1
      }

Thanks!

Upvotes: 0

Views: 307

Answers (1)

nico
nico

Reputation: 51640

You can use:

i <- which(a==-1)[1]

which(a==-1) returns all the indices of the elements of the vector or matrix a which are equal to -1. You only want the first one, so take element 1 of the resulting array.

Note: this returns NA if the matrix a does not have any -1 element

Upvotes: 2

Related Questions