user3294195 user3294195 - 1 month ago 18
C Question

C array to Rcpp NumericVector

I am working with C arrays, and I need to convert them to

Rcpp::NumericVector
at some point in my code. I tried the following code but it throws an error (cannot convert from double [5] to type 'SEXP'). What is the right way to convert from a C array to
NumericVector
?

library(Rcpp)
cppFunction(
'
NumericVector fun() {
double data[5] = {1.0, 2.0. 1.0, 2.0, 1.0};
return as<NumericVector>(data);
}
')

Answer

I know of two ways this can be done:

1: range constructor

cppFunction('
    NumericVector fun() {
        double data[5] = {1.0,2.0,1.0,2.0,1.0};
        return NumericVector(data,data+sizeof(data)/sizeof(*data));
    }
');
fun();
## [1] 1 2 1 2 1

2: build an STL vector, wrap in an SEXP, and finally wrap in NumericVector

cppFunction('
    NumericVector fun() {
        double data[5] = {1.0,2.0,1.0,2.0,1.0};
        return as<NumericVector>(wrap(std::vector<double>(data,data+sizeof(data)/sizeof(*data))));
    }
');
fun();
## [1] 1 2 1 2 1