找出向量中的第一个最大出现

时间:2018-09-27 09:29:00

标签: r

假设我有一个向量

x <- c(300, 320, 342, 355, 399, 453, 500, 532, 2, 3, 4, 5, 100, 300, 500, 550, 2, 3)

如您所见,它的值有些增加,然后值减小,然后又增加,依此类推。

发现第一个下降的点是值532,然后是值2.因此,在这一点上,我想将值2加到532,所以我现在有534,然后将值3加到534。值4,然后值5,依此类推。

所以,我累加了第一次最大出现后的值532。

所以,我的结果将是:

300, 320, 342, 355, 399, 453, 500, 532, 534, 537, 541, 546, 646, 964, 1446, 1996, 1998 , 2001

我正在尝试:

MY_FUNC <- function(Values)
{

    Values <- Values[!is.na(Values)]

    max_val = 0
    index = 0;
    for (i in 1:length(Values))
    {
        if (Values[i] > max_val)
        {
            max_val = Values[i]
            index = i;
            #break when first occurence found
        }
    }
    new_vec <- Values[index] + cumsum(Values[(index + 1):length(Values)])
    new_vec

}

x <- c(300, 320, 342, 355, 399, 453, 500, 532, 2, 3, 4, 5, 100, 300, 500, 550, 2, 3)
MY_FUNC(x)

但是我不知道如何找到循环的第一个最大出现和中断。

1 个答案:

答案 0 :(得分:4)

我们可以使用diffwhich.max查找第一个值下降,然后将该点之前的值与该点之后的cumsum个值连接在一起。

first_drop <- which.max(diff(x) < 0)
c(x[1:(first_drop - 1)], cumsum(x[first_drop:length(x)]))

#[1]  300  320  342  355  399  453  500  532  534  537  541  546  646  946 1446 1996
#[17] 1998 2001

如果需要,我们可以在函数中编写

MY_FUNC <- function(x) {
  first_drop <- which.max(diff(x) < 0)
  c(x[1:(first_drop - 1)], cumsum(x[first_drop:length(x)]))
}

MY_FUNC(x)
# [1]  300  320  342  355  399  453  500  532  534  537  541  546  646  946 1446
#[16] 1996 1998 2001
相关问题