Search code examples
rrcpp

R Rcpp how to use a vector in pow


I want to convert R code with a power element (x^y) to Rcpp. Rcpp uses pow(x,y) but it appears to not be vectorized. The following example returns NaN NaN.

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
NumericVector vecTest(NumericVector x) {
  
  return pow(x, 0.25);
}

/*** R
test <- c(-1.19556e+12, -1.24111e+12)
vecTest(test)
*/

I can write a for loop that would step through the elements of the x vector but I'm wondering if there is something I'm just missing.


Solution

  • It sometimes helps to

    • look at the header file defining the function you want to use

    • look at some unit tests deploying the function you want to use

    • keep your examples simple

    • vary the arguments a little

    • be sure you hit the function from the namespace you want to hit

    Code

    #include <Rcpp.h>
    
    // [[Rcpp::export]]
    Rcpp::NumericVector mypow(Rcpp::NumericVector x, double expo) {
        return Rcpp::pow(x, expo);
    }
    
    /*** R
    v <- c(2, 3, 4, 1.2e12, -1.2e12)
    mypow(v, 2)
    mypow(v, 0.5)
    */
    

    Output

    > Rcpp::sourceCpp("~/git/stackoverflow/68852817/answer.cpp")
    
    > v <- c(2,3,4)
    
    > mypow(v, 2)
    [1] 4.00e+00 9.00e+00 1.60e+01 1.44e+24 1.44e+24
    
    > mypow(v, 0.5)
    [1] 1.41421e+00 1.73205e+00 2.00000e+00 1.09545e+06         NaN
    > 
    

    Seems to work as advertised. Vector argument for exponentiation by a scalar.

    Edit: Updated to show some 'large' values in your example. Roots of negative reals don't work, but that is a math issue and not a question of the compiler, library or package.