我想在整个向量上返回向量位置的索引。
例如,
a = c(0,10,20,30) #lower bound
b = c(10,20,30,40) #upper bound
values = c(1,5,24,30)
#I want idx to return the index of a/b across all elements in values
# I was hoping this would work:
idx = which(a<=values & b>values)
#I can get it if I do a for loop but I want to avoid a for loop
idx = c(0)
for(i in 1:length(values)){
idx[i]= which(a<=values[i] & b>values[i])
}
只是为了对此问题提出答案。
findInterval(values, unique(c(a, b)))
henrik的答案使用较不知名的功能findInterval
从基本包装中使用。此功能具有几种可能使其适应大多数情况的参数。
sapply(values, function(x) which(a<=x & b>x))
D.P的答案将OP的循环调整为在sapply
中工作。如果您不记得findInterval
,或者您只想直接控制正在发生的事情,这可能是一个更好的选择。