Which.max () does not return NA

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

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 exceeds 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 can I change this expression to get NA as a result?

+6
source share
1 answer

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() does not work, you must understand how R which.max() your values ​​from a number to a logical to a numeric one.

 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 
+12
source

Source: https://habr.com/ru/post/948435/


All Articles