Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
超过阈值时如何使用 cumsum 返回索引?
v <- c(1,5,7,9,10,14,16,17) Threshold <- 10
该函数将返回 3,因为累积和将大于 10,这提供了 e 索引 3 作为结果。
我们可以使用which
which
which(cumsum(v)>Threshold)[1] #[1] 3
或者which.max
which.max
which.max(cumsum(v)>Threshold) #[1] 3
或者正如@nicola 评论的那样findInterval是另一种选择。优点是它是矢量化的,可用于一次检查多个阈值。
findInterval
findInterval(Threshold,cumsum(v))+1 #[1] 3 findInterval(c(10,49), cumsum(v))+1 #[1] 3 7