2015-07-20 79 views
1

如何在超过阈值时使用cumsum返回索引?R中的Cumsum向量

v <- c(1,5,7,9,10,14,16,17) 
Threshold <- 10 

该函数将返回3,因为累计和会大于10,从而提供e索引3作为结果。

回答

6

我们可以使用which

which(cumsum(v)>Threshold)[1] 
#[1] 3 

或者which.max

which.max(cumsum(v)>Threshold) 
#[1] 3 

或者作为@nicola评论findInterval是另一种选择。优点是它是矢量化的,可以用来一次检查多个阈值。

findInterval(Threshold,cumsum(v))+1 
#[1] 3 
findInterval(c(10,49), cumsum(v))+1 
#[1] 3 7 
+1

@nicola感谢findInterval – akrun