Question Details

No question body available.

Tags

r vector indexing

Answers (3)

June 17, 2026 Score: 4 Rep: 274,516 Quality: Medium Completeness: 50%

Get the indexes of the satisfying elements and take the last one:

# 1 tail(which(v < 8), 1)
[1] 7

The above gives a zero length result if there are no satisfying elements. To specify a different result use this (where we have specified NA but that can be replaced with any other desired value such as 0, say):

# 2 (v < 0) |> which() |> tail(1) |> c(NA) |> head(1)
[1] NA

or

# 3 (v < 0) |> which() |> (\(x) if (length(x)) tail(x, 1) else NA)()
[1] NA

This one gives NA if there is no match:

# 4 rev(which(v < 0))[1]
[1] NA

This one gives 0 if there is no match. It is less efficient than the ones above but this may not matter if v is not large.

# 5 Reduce(max, init = 0, which(v < 0))
[1] 0
June 17, 2026 Score: 2 Rep: 8,808 Quality: Low Completeness: 40%

You can supply a condition to which(), which returns index values that match the condition. So:

which(v < 8) #[1] 1 2 3 6 7

To get the index of the last value < 8, wrap it in max() e.g.:

max(which(v < 8)) #[1] 7
June 17, 2026 Score: 1 Rep: 12,355 Quality: Low Completeness: 40%

We might want to use Position(), one of those Common Higher-Order Functions in Functional Programming Languages which we tend to forget.

Position(\(x) x