I have an R::NumericVector and I was wondering if it was possible to convert it to an std::vector without using a loop in c++.
void someFunction(NumericMatrix mtx){
NumericVector rVec = mtx.row(0);
std::vector<int> sVec;
sVec = rVec; //<-- I wanna do something like this
}
Yes, see eg Section 3 of the Introduction to Rcpp vignette about as<>()
. This is pretty much in every intro ever written about Rcpp and hard to miss.
Worked example below (with manual indentation; code is just one long line).
R> cppFunction("std::vector<double> foo(NumericMatrix M) {
NumericVector a = M.row(0);
std::vector<double> b = as<std::vector<double> >(a);
return b;
}")
R> foo(matrix(1:9, 3, 3))
[1] 1 4 7
R>
Sure, just allocate the std::vector
and fill it.
test.cpp
#include <Rcpp.h>
// [[Rcpp::export]]
void someFunction(Rcpp::NumericMatrix mat){
Rcpp::NumericVector vec = mat.row(0);
std::vector<double> X(vec.begin(),vec.end());
for (unsigned int i = 0; i<X.size(); i++) {
std::cout << "X[" << i << "] = " << X.at(i) << std::endl;
}
}
test.R
library(Rcpp)
sourceCpp('test.cpp')
mat <- matrix(rnorm(16), 4, 4)
someFunction(mat)
You could also just use the as
function
std::vector<double> X = Rcpp::as<std::vector<double> >(vec);
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