Rcpp - 用二进制函数转换数字向量?



我正在考虑通过C++重写并通过Rcpp集成来加速一些R代码。 至少可以说,我的 Cpp 生锈了:所以任何建议都非常感谢。 特别是,我正在寻找将函数映射到 RcppNumericVector的所有元素的指针。 下面是一个示例。

我需要生成一个新向量,如下所示:

  • 从现有NumericVectortail切片;
  • 用除数除以新切片的每个元素

到目前为止,我有这个:

// [[Rcpp::export]]
NumericVector cppAdjustProbabilities(  NumericVector& currentProbs, 
const int index,
const double divisor ) {
//Note index <=0, e.g. -1 means remove first element
if(index == 0) {
return(currentProbs);
} else {
NumericVector newProbs = no_init(currentProbs.size()+index);                 
NumericVector::iterator i = currentProbs.begin() - index; 
NumericVector::iterator j = newProbs.begin();
for(; i != currentProbs.end(); ++i, ++j) {
*j=*i/divisor;
}    
return(newProbs);
}
}

这有效,但我更喜欢使用"地图"方法。 我看了std::transform,但它只支持对向量元素的一元运算 - 所以我看不到如何将除数传入。 例如,这是无效的:

std::transform(currentProbs.begin()-index, currentProbs.end(),
newProbs.begin(), [](double val) { return (val / divisor);} );

有没有办法将divisor纳入 lambda 的范围?还是另一种方式?

谢谢

使用 c++ lambda 函数,您可以捕获如下值:

src1 <- 'NumericVector cppAdjustProbabilities(  NumericVector& currentProbs, 
const int index,
const double divisor ) {
//Note index <=0, e.g. -1 means remove first element
if(index == 0) {
return(currentProbs);
} else {
NumericVector newProbs = no_init(currentProbs.size()+index);
std::transform(currentProbs.begin()-index, currentProbs.end(),
newProbs.begin(), [&divisor](double val) { return (val / divisor);} );
//                 ^^^^^^^^
return(newProbs);
}
}'
Rcpp::cppFunction(src1)
currentProbs <- c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
index <- -5L
divisor <- 2.0
cppAdjustProbabilities(currentProbs, index, divisor)
#> [1] 0.30 0.35 0.40 0.45

最新更新