![](/img/trans.png)
[英]How can I find the position of the first value of every matrixrow that equals or is greater than a pre-defined value?
[英]Find position of first value greater than X in a vector
在 R 中:我有一個向量,想找到第一個大於 100 的值的位置。
# Randomly generate a suitable vector
set.seed(0)
v <- sample(50:150, size = 50, replace = TRUE)
min(which(v > 100))
大多數基於which
和max
答案在遍歷整個向量時都很慢(尤其是對於長向量):
x>100
評估向量中的每個值以查看它是否與條件匹配which
和max
/ min
搜索所有在第 1 步返回的索引。並找到最大值/最小值 Position
只會評估條件,直到遇到第一個 TRUE 值並立即返回相應的索引,而不會繼續遍歷向量的其余部分。
# Randomly generate a suitable vector
v <- sample(50:150, size = 50, replace = TRUE)
Position(function(x) x > 100, v)
查看which.max
:
x <- seq(1, 150, 3)
which.max(x > 100)
# [1] 35
x[35]
# [1] 103
detect_index
提一下,Hadley Wickham 已經實現了一個函數detect_index
來在他的用於函數式編程的purrr
包中完成這個任務。
我最近自己使用了detect_index
並將其推薦給其他有同樣問題的人。
可在此處找到檢測detect_index
文檔: https : detect_index
有很多解決方案,另一個是:
x <- 90:110
which(x > 100)[1]
假設值是您的向量。
firstGreatearThan <- NULL
for(i in seq(along=values)) {
if(values[i] > 100) {
firstGreatearThan <- i
break
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.