2013-06-30 61 views
6

我有一堆包含0和1之間的數字,我需要找到的第一個元素的超過一定值r索引有序向量:which.max()不返回NA

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結果?

回答

12

只需使用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 
+0

謝謝你們的回答和解釋! – ap53