如何对向量(例如cumsum
)进行累加求和,但是有界以使求和总是低于下限或高于上限?
标准的cumsum函数将导致以下结果.
foo <- c(100, -200, 400, 200)
cumsum(foo)
# [1] 100 -100 300 500
Run Code Online (Sandbox Code Playgroud)
我正在寻找像基本cumsum
功能一样高效的东西.我希望输出看起来如下.
cumsum.bounded(foo, lower.bound = 0, upper.bound = 500)
# [1] 100 0 400 500
Run Code Online (Sandbox Code Playgroud)
谢谢
jos*_*ber 12
正如评论中所提到的,Rcpp
是一个很好的方法.
cumsumBounded.cpp
:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector cumsumBounded(NumericVector x, double low, double high) {
NumericVector res(x.size());
double acc = 0;
for (int i=0; i < x.size(); ++i) {
acc += x[i];
if (acc < low) acc = low;
else if (acc > high) acc = high;
res[i] = acc;
}
return res;
}
Run Code Online (Sandbox Code Playgroud)
编译并使用新功能:
library(Rcpp)
sourceCpp(file="cumsumBounded.cpp")
foo <- c(100, -200, 400, 200)
cumsumBounded(foo, 0, 500)
# [1] 100 0 400 500
Run Code Online (Sandbox Code Playgroud)
我想这可能会奏效。
library ("Rcpp")
cumsum.bounded <- cppFunction(
'NumericVector cumsum_bounded (NumericVector x, const double lower, const double upper) {
double acc = 0;
NumericVector result(x.size());
for(int i = 0; i < x.size(); i++) {
acc += x[i];
if (acc < lower) acc = lower;
if (acc > upper) acc = upper;
result[i] = acc;
}
return result;
}')
Run Code Online (Sandbox Code Playgroud)