【问题标题】:Cumsum in R for vectorR中的Cumsum用于向量
【发布时间】:2015-07-20 06:30:08
【问题描述】:

当超过阈值时如何使用 cumsum 返回索引?

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

该函数将返回 3,因为累积和刚好大于 10,这提供了 e 索引 3 作为结果。

【问题讨论】:

    标签: r dataframe cumsum


    【解决方案1】:

    我们可以使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-02
      • 1970-01-01
      • 2015-06-21
      • 1970-01-01
      • 1970-01-01
      • 2016-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多