2015-05-07 45 views
3

Rcpp允許矢量化一些操作,這很好。但是對於pow,只有基數可以是一個向量,而不是指數。通常情況下,在編譯:Rcpp中pow的矢量化指數

#include <Rcpp.h> 
using namespace Rcpp; 
// [[Rcpp::export]] 
NumericVector puissancedCpp(NumericVector base, double exp){ 
    return pow(base,exp); 
} 

作品,但不是:

#include <Rcpp.h> 
using namespace Rcpp; 
// [[Rcpp::export]] 
NumericVector puissancedCpp(NumericVector base, NumericVector exp){ 
    return pow(base,exp); 
} 

什麼是執行的推薦方式中的R這將是:在其他東西中間

c(0,1,2,3)^c(4,3,2,1) 

在C完成?

回答

4

這裏有一個選項,假設你的編譯器支持C++ 11:

#include <Rcpp.h> 
// [[Rcpp::plugins(cpp11)]] 

// [[Rcpp::export]] 
std::vector<double> vpow(const std::vector<double>& base, const std::vector<double>& exp) { 
    std::vector<double> res(base.size()); 
    std::transform(base.begin(), base.end(), exp.begin(), res.begin(), 
        [&](double lhs, double rhs) -> double { 
        return std::pow(lhs, rhs); 
        }); 
    return res; 
} 


/*** R 

c(0,1,2,3)^c(4,3,2,1) 
#[1] 0 1 4 3 
vpow(0:3, c(4,3,2,1)) 
#[1] 0 1 4 3 

*/ 

如果你正在使用舊的編譯器工作時,你可以使用

double dpow(const double lhs, const double rhs) { 
    return std::pow(lhs, rhs); 
} 

// [[Rcpp::export]] 
std::vector<double> vpow98(const std::vector<double>& base, const std::vector<double>& exp) { 
    std::vector<double> res(base.size()); 
    std::transform(base.begin(), base.end(), exp.begin(), res.begin(), dpow); 
    return res; 
} 
+2

非常好。 Rcpp的重點在於使這一切變得簡單。 –

+1

太好了。它適用於我的Ubuntu 14.04盒 – cmbarbu

+1

當然。我們通過插件支持C++ 11一段時間 - 也許是13.04或12.10。目前的g ++ 4.9。*很好。 –

9

一個實現這一如果您由於某種原因不能使用C++ 11,則可以選擇替代方案11

#include <Rcpp.h> 

using namespace Rcpp; 

// [[Rcpp::export]] 
NumericVector vecpow(const NumericVector base, const NumericVector exp) { 
    NumericVector out(base.size()); 
    std::transform(base.begin(), base.end(), 
       exp.begin(), out.begin(), ::pow); 
    return out; 
} 

/*** R 
vecpow(c(0:3), c(4:1)) 
***/ 

哪產生

R> Rcpp::sourceCpp("vecpow.cpp") 

R> vecpow(c(0:3), c(4:1)) 
[1] 0 1 4 3 
R> 
+0

超好看。這實際上是由於某種原因,我甚至比nrussel的答案快了10% – cmbarbu

+0

更快,因爲它使用本機Rcpp類型,因此避免了底層數據與STL容器之間的副本。 –