which.max()不返回NA

ap5*_*p53 6 r

我有一堆有序的向量,包含0到1之间的数字.我需要找到第一个元素的索引超过某个值r:

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

现在,如果我的目标值超过向量中的最大值,则.max()返回1,这可能与"真实"第一个值混淆:

which.max(x >= 0)
[1] 1
which.max(x >= 0.9) # Why?
[1] 1
Run Code Online (Sandbox Code Playgroud)

我如何修改此表达式以获得NA作为结果?

And*_*rie 12

只需使用which()并返回第一个元素:

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

which(x > 0.9)[1]
[1] NA
Run Code Online (Sandbox Code Playgroud)

要理解为什么which.max()不起作用,您必须了解R如何将您的值从数字强制转换为逻辑到数字.

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
Run Code Online (Sandbox Code Playgroud)