Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert R::vector to std::vector [closed]

Tags:

r

stdvector

rcpp

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
}
like image 512
Allen Huang Avatar asked Dec 24 '22 05:12

Allen Huang


2 Answers

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> 
like image 106
Dirk Eddelbuettel Avatar answered Jan 05 '23 08:01

Dirk Eddelbuettel


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);
like image 41
cdeterman Avatar answered Jan 05 '23 08:01

cdeterman