简体   繁体   English

R中的向量求和

[英]Cumsum in R for vector

How can I use cumsum to return the index when a threshold is crossed? 超过阈值时,如何使用cumsum返回索引?

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

The function would return 3 as the cumulative sum would just be larger than 10, which provides the e index 3 as result. 该函数将返回3,因为累计总和将刚好大于10,从而提供e索引3。

We could use which 我们可以使用which

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

Or which.max which.max

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

Or as @nicola commented findInterval is another option. 或如@nicola所评论, findInterval是另一种选择。 The advantage is it is vectorized and can be used to check multiple Threshold values at once. 优点是它已向量化,可用于一次检查多个阈值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM