2017-02-19 87 views
2

例如我有以下代码:断裂cumsum()函数

cumsum(1:100) 

并且我想要打破它,如果一个元素i + 1会比3000更大。我怎样才能做到这一点?

因此,不是这样的结果:

[1] 1 3 6 10 15 21 28 36 45 55 66 78 91 105 120 136 153 171 190 210 231 253 276 300 
[25] 325 351 378 406 435 465 496 528 561 595 630 666 703 741 780 820 861 903 946 990 1035 1081 1128 1176 
[49] 1225 1275 1326 1378 1431 1485 1540 1596 1653 1711 1770 1830 1891 1953 2016 2080 2145 2211 2278 2346 2415 2485 2556 2628 
[73] 2701 2775 2850 2926 3003 3081 3160 3240 3321 3403 3486 3570 3655 3741 3828 3916 4005 4095 4186 4278 4371 4465 4560 4656 
[97] 4753 4851 4950 5050 

我希望得到以下结果:

[1] 1 3 6 10 15 21 28 36 45 55 66 78 91 105 120 136 153 171 190 210 231 253 276 300 
[25] 325 351 378 406 435 465 496 528 561 595 630 666 703 741 780 820 861 903 946 990 1035 1081 1128 1176 
[49] 1225 1275 1326 1378 1431 1485 1540 1596 1653 1711 1770 1830 1891 1953 2016 2080 2145 2211 2278 2346 2415 2485 2556 2628 
[73] 2701 2775 2850 2926 
+2

没有什么R中,我所知道的内置。你可能很容易在Rcpp中写一些东西。 –

回答

4

正如我在评论中提到,写一些简单的RCPP即使对于像我这样不应该是一个大问题。这里有一个,似乎工作(感谢@ MatthewLundberg的改进建议)非常原始的实现

library(Rcpp) 
cppFunction('NumericVector cumsumCPP(NumericVector x, int y = 0){ 

    // y = 0 is the default 
    // Need to do this in order to avoid modifying the original x 
    int n = x.size(); 
    NumericVector res(n); 
    res[0] = x[0]; 

    for (int i = 1 ; i < n ; i++) { 
     res[i] = res[i - 1] + x[i]; 
     if (res[i] > y && (y != 0)) { 
     // This breaks the loop if condition met 
     return res[seq(0, i - 1)]; 
     } 
    } 

    // This handles cases when y== 0 OR y != 0 and y > cumsum(res) 
    return res; 
}') 

cumsumCPP(1:100, 3000) 
# [1] 1 3 6 10 15 21 28 36 45 55 66 78 91 105 120 136 153 171 190 210 231 253 276 300 
# [25] 325 351 378 406 435 465 496 528 561 595 630 666 703 741 780 820 861 903 946 990 1035 1081 1128 1176 
# [49] 1225 1275 1326 1378 1431 1485 1540 1596 1653 1711 1770 1830 1891 1953 2016 2080 2145 2211 2278 2346 2415 2485 2556 2628 
# [73] 2701 2775 2850 2926 

同样基地卢比cumsum,这同时适用于整数和浮点数,不处理NA秒。 treshhold的默认值设置为0 - 如果您想限制负值cumsum,这并不理想,但现在我想不出任何更好的值(您可以自行决定)。

虽然可以使用一些优化...

set.seed(123) 
x <- as.numeric(sample(1:1e3, 1e7, replace = TRUE)) 
microbenchmark::microbenchmark(cumsum(x), cumsumCPP(x)) 
# Unit: milliseconds 
#   expr  min  lq  mean median  uq  max neval cld 
# cumsum(x) 58.61942 61.46836 72.50915 76.7568 80.97435 99.01264 100 a 
# cumsumCPP(x) 98.44499 100.09979 110.45626 112.1552 119.22958 131.97619 100 b 

identical(cumsum(x), cumsumCPP(x)) 
## [1] TRUE 
+1

您可以通过将内部测试更改为'if(y && res [i]> y)来移除外部“if”。 –

+0

Thanks @MatthewLundberg,编辑。 –

+0

@DavidArenburg感谢您对我的回答(使用base R)的评论。你是对的 - 我完全错误地测试了它。已删除,以免别人误入歧途! –

1

我们可以在cumsum输出使用<=

v1[v1 <=3000] 

或者另一个o ption是

setdiff(pmin(cumsum(1:100), 3000), 3000) 

其中

v1 <- cumsum(1:100)