Phi*_*hil 31
# Randomly generate a suitable vector
set.seed(0)
v <- sample(50:150, size = 50, replace = TRUE)
min(which(v > 100))
Run Code Online (Sandbox Code Playgroud)
Ant*_*Ant 24
大多数答案基于which并且max很慢(特别是对于长向量),因为它们遍历整个向量:
x>100计算向量中的每个值以查看它是否与条件匹配which和max/ min搜索在步骤1返回的所有索引并找到最大值/最小值Position 只会评估条件,直到它遇到第一个TRUE值并立即返回相应的索引,而不继续通过向量的其余部分.
which
luk*_*keA 12
退房which.max:
x <- seq(1, 150, 3)
which.max(x > 100)
# [1] 35
x[35]
# [1] 103
Run Code Online (Sandbox Code Playgroud)
仅需提及,Hadley Wickham已实现了函数detect_index,以在其purrr用于函数式编程的程序包中精确地完成此任务。
我最近使用detect_index自己,会推荐给其他有相同问题的人。
的文档detect_index可以在这里找到:https : //rdrr.io/cran/purrr/man/detect.html