R:累计和条件

时间:2018-02-14 11:34:25

标签: r cumsum

假设我需要采用向量的累积和

  set.seed(123)

  x <- sample(-5:5, 15,replace = T)
  x
  -2  3 -1  4  5 -5  0  4  1  0  5 -1  2  1 -4

x是15天的值,第一个值属于第1天

我可以把x的缩写作为

   cumsum(x)

   -2  1  0  4  9  4  4  8  9  9 14 13 15 16 12

然而,我想强加的条件是,在任何一天,cumsum不能超过10或否定。如果一天超过10,将其设为10,或者如果它小于零,则将其设为零。

我这样做了:

  ifelse(10 + cumsum(x) < 0, 0, ifelse(10 + cumsum(x) > 10, 10,cumsum(x)))

  -2 10  0 10 10 10 10 10 10 10 10 10 10 10 10

这不能给我正确答案,因为我的第一个值是负值,而小于10的值被转换成10.我做错了什么?

修改

  if this is x,           -2,3,-1,4,5,-5,0,4,1,0,5,-1,2,1,-4
  then the calculation is: 8 (10 - 2= 8)
                           10 (8 + 3 = 11, converted into 10)
                           9 (10 - 1 = 9)
                          10 (9 + 4 = 13, converted into 10)
                          10 (10 + 5 = 15, converted into 10)
                           5 (10 - 5 = 5)
                           5 (5 + 0 = 5)
                           9 (5 + 4 = 9)
                          10 (9 + 1 = 10)
                          10 (10 + 0 = 10)
                          10 (10 + 5 = 15, converted into 10)
                           9 (10 - 1 = 9)
                          10 (9 + 2 = 11, converted into 10)
                          10 (10 + 1 = 11, converted into 10)
                          6 (10 -4 = 6)  

最终答案应该是:

                   8, 10, 9, 10, 10, 5,5,9,10,10,10,9,10,10,6

0 个答案:

没有答案
相关问题