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);
}
')
                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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With