Martin Schmelzer
Martin Schmelzer

Reputation: 23919

Rcpp: Multiply two NumericVectors while subsetting one of them

I have two NumericVectors A and B. The following multiplication works fine when subsetting the vector B beforehand:

NumericVector B_sub  = B[A - 1];
NumericVector res    = A * B_sub;

When I try to do

NumericVector res = A * B[A - 1];

it yields the error

invalid operands to binary expression ('NumericVector' (aka 'Vector<14>') and 'SubsetProxy<14, PreserveStorage, 14, true, Rcpp::sugar::Minus_Vector_Primitive<14, true, Rcpp::Vector<14, PreserveStorage> > >')

I suppose this is a common error type in C++. I am an economics student who is involved with R and python but C++ is a new world for me.

So why is this operation not valid using Rcpp syntactic sugar? Is there a way to make it possible using a type conversion or something similar?


Here is a reproducible myFun.cpp file:

#include <Rcpp.h>

using namespace std;
using namespace Rcpp;

// [[Rcpp::export]]
NumericVector myFun(NumericVector B) {
  NumericVector A      = wrap(seq_len(B.size()));
  NumericVector B_sub  = B[A - 1];
  NumericVector res    = A * B_sub;
  // NumericVector res = A * B[A - 1];
  return res;
}

and the R-Code to use myFun:

library(Rcpp)
sourceCpp("myFun.cpp")
myFun(1:10)

Upvotes: 1

Views: 463

Answers (1)

duckmayr
duckmayr

Reputation: 16940

You can use as<NumericVector>(). Create the following "myFun.cpp":

#include <Rcpp.h>

using namespace Rcpp;

// [[Rcpp::export]]
NumericVector myFun(NumericVector B) {
    NumericVector A   = wrap(seq_len(B.size()));
    NumericVector res = A * as<NumericVector>(B[A - 1]);
    return res;
}

/*** R
myFun(1:10)
*/

Then source and see the results:

library(Rcpp)
sourceCpp("myFun.cpp")

> myFun(1:10)
 [1]   1   4   9  16  25  36  49  64  81 100

Upvotes: 1

Related Questions