Carl
Carl

Reputation: 311

What is the quickest way to verify whether the first 10 elements of a vector are non-zero in R?

Suppose we have a 300 x 1000 matrix. If there exists any row of this matrix such that the first 10 elements of the row are non-zero, then a condition is satisfied. What is the quickest way to write this code instead of doing it using for loops?

Upvotes: 4

Views: 49

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145755

any(apply(m[, 1:10], MARGIN = 1, function(x) all(x != 0))) should be pretty quick.

Upvotes: 4

Related Questions