在R中,假设多个条件向量,如何返回向量的索引向量



我想在整个向量上返回向量位置的索引。

例如,

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,或者您只想直接控制正在发生的事情,这可能是一个更好的选择。

最新更新