【发布时间】:2015-07-20 06:30:08
【问题描述】:
当超过阈值时如何使用 cumsum 返回索引?
v <- c(1,5,7,9,10,14,16,17)
Threshold <- 10
该函数将返回 3,因为累积和刚好大于 10,这提供了 e 索引 3 作为结果。
【问题讨论】:
当超过阈值时如何使用 cumsum 返回索引?
v <- c(1,5,7,9,10,14,16,17)
Threshold <- 10
该函数将返回 3,因为累积和刚好大于 10,这提供了 e 索引 3 作为结果。
【问题讨论】:
我们可以使用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
【讨论】: