ap53
ap53

Reputation: 823

which.max() does not return NA

I have a bunch of ordered vectors containing numbers between 0 and 1. I need to find the index of the first element over a certain value r:

x <- c(0.1, 0.3, 0.4, 0.8)
which.max(x >= 0.4)
[1] 3  # This is exactly what I need

Now if my target value is over the maximum value in the vector, which.max() returns 1, which can be confused with the "real" first value:

which.max(x >= 0)
[1] 1
which.max(x >= 0.9) # Why?
[1] 1

How could I modify this expression to get an NA as a result?

Upvotes: 6

Views: 3325

Answers (1)

Andrie
Andrie

Reputation: 179518

Just use which() and return the first element:

which(x > 0.3)[1]
[1] 3

which(x > 0.9)[1]
[1] NA

To understand why which.max() doesn't work, you have to understand how R coerces your values from numeric to logical to numeric.

x > 0.9
[1] FALSE FALSE FALSE FALSE

as.numeric(x > 0.9)
[1] 0 0 0 0

max(as.numeric(x > 0.9))
[1] 0

which.max(as.numeric(x > 0.9))
[1] 1

Upvotes: 12

Related Questions