将Rcpp::NumericVector转换为Eigen::VectorXd

convert Rcpp::NumericVector to Eigen::VectorXd

本文关键字:Eigen VectorXd NumericVector Rcpp 转换      更新时间:2023-10-16

以前也有人问过类似的问题:

在Rcpp(Eigen)中进行NumericVector/Matrix和VectorXd/MatrixXd之间的转换以执行Cholesky求解

问题是,我在fastLm.cpp(最后)中找到的代码对我不起作用。
Rcpp::NumericVector X( (SEXP) R.parseEval("x <- 1:10"));
Eigen::Map<Eigen::VectorXd> XS(Rcpp::as<Eigen::Map<Eigen::VectorXd>>(X)); //!!not working

给出如下错误:

error: no matching constructor for initialization of 'Eigen::Map<Eigen::Matrix<double, -1, 1, 0, -1, 1>, 0, Eigen::Stride<0, 0> >'
                    Exporter( SEXP x ) : t(x){}

和(除其他):

note: candidate constructor (the implicit copy constructor) not viable: cannot convert argument of incomplete type 'SEXP' (aka 'SEXPREC *') to 'const Eigen::Map<Eigen::Matrix<double, -1, 1, 0, -1, 1>, 0, Eigen::Stride<0, 0> >'
template<typename PlainObjectType, int MapOptions, typename StrideType> class Map

它可能与SEXP对象有关?

如果我在>>:

之间再加一个空格,就可以了
R> cppFunction("bool conv(NumericVector X) { 
      Eigen::Map<Eigen::VectorXd> 
      XS(Rcpp::as<Eigen::Map<Eigen::VectorXd> >(X)); return true; } ", 
           depends="RcppEigen")
R> conv(1:4)
[1] TRUE
R>

而且,我认为你不能直接说

X((SEXP) R.parseEval("x <- 1:10"))

,除非您使用RInside,它有自己的Eigen示例——为此只需执行

cd examples/eigen
make
./rinside_sample0
./rinside_sample1

在我的安装中仍然可以正常运行。