jmmcnew
jmmcnew

Reputation: 120

R: Search a vector from end forward

A newbie question here. I have a vector v. I would like to search the vector from the end forward to find the last instance a condition is true. In matlab I would call find(condition, 1, 'last') and the search would start from the end of the vector and move forward. Is there an equivalent call in R?

For instance, I might like to know the last time v < v[length(v)]. I know that max(which(v<v[length(v)])) gives the correct answer. However speed is important, and it seems as if this first returns all the indices meeting the condition v

Upvotes: 2

Views: 400

Answers (1)

J. Win.
J. Win.

Reputation: 6771

Generally in R it is preferred that you run a function "vectorized" on the entire vector, rather than in a loop that lets you stop as soon as a condition is true. However, the function rev will reverse a vector and might be handy for what you want to do.

Upvotes: 4

Related Questions