我有一堆有序向量,其中包含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
现在,如果我的目标值超过向量中的最大值,则which.max()返回1,即
可以与“实际”第一个值混淆:
which.max(x >= 0)
[1] 1
which.max(x >= 0.9) # Why?
[1] 1
如何修改此表达式以得到NA?
最佳答案
只需使用which()
并返回第一个元素:
which(x > 0.3)[1]
[1] 3
which(x > 0.9)[1]
[1] NA
要了解
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
关于r - which.max()不返回NA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17394909/