[英]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))
Most answers based on which
and max
are slow (especially for long vectors) as they iterate through the entire vector:大多数基于which
和max
答案在遍历整个向量时都很慢(尤其是对于长向量):
x>100
evaluates every value in the vector to see if it matches the condition x>100
评估向量中的每个值以查看它是否与条件匹配which
and max
/ min
search all the indexes returned at step 1. and find the maximum/minimum which
和max
/ min
搜索所有在第 1 步返回的索引。并找到最大值/最小值Position
will only evaluate the condition until it encounters the first TRUE value and immediately return the corresponding index, without continuing through the rest of the vector. Position
只会评估条件,直到遇到第一个 TRUE 值并立即返回相应的索引,而不会继续遍历向量的其余部分。
# Randomly generate a suitable vector
v <- sample(50:150, size = 50, replace = TRUE)
Position(function(x) x > 100, v)
Check out which.max
:查看which.max
:
x <- seq(1, 150, 3)
which.max(x > 100)
# [1] 35
x[35]
# [1] 103
Just to mention, Hadley Wickham has implemented a function, detect_index
, to do exactly this task in his purrr
package for functional programming. detect_index
提一下,Hadley Wickham 已经实现了一个函数detect_index
来在他的用于函数式编程的purrr
包中完成这个任务。
I recently used detect_index
myself and would recommend it to anyone else with the same problem.我最近自己使用了detect_index
并将其推荐给其他有同样问题的人。
Documentation for detect_index
can be found here: https://rdrr.io/cran/purrr/man/detect.html可在此处找到检测detect_index
文档: https : detect_index
There are many solutions, another is:有很多解决方案,另一个是:
x <- 90:110
which(x > 100)[1]
Assuming values is your vector.假设值是您的向量。
firstGreatearThan <- NULL
for(i in seq(along=values)) {
if(values[i] > 100) {
firstGreatearThan <- i
break
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.