Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Rcpp allows to vectorize some operations, which is great. But for pow only the base number can be a vector, not the exponent. Typically, on compilation:

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

works but not:

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

What would be the recommended way to perform what in R would be:

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

in the middle of other things done in C?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

An alternative if you for some reason can't use C++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))
***/

which produces

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...