4

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);
}
')
0

1 Answer 1

7

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
1
  • Form 1 is preferred. Iterator-alike reference to the beginning of content plus its extent. That has all been documented since the very beginning too. If I tried hard enough I am sure I could find earlier post here too... Nov 6, 2016 at 15:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.