一切似乎都在我的包中工作,但我想检查其步骤是否正确以及使用“Map”的内存使用情况。 (这是一个简单的示例,位于内联示例和fastLm()
例子。)
这是一个内联函数,它取矩阵每一列的最大值:
library(Rcpp);
library(inline);
library(RcppEigen);
maxOverColCpp <- '
using Eigen::Map;
using Eigen::MatrixXd;
// Map the double matrix AA from R
const Map<MatrixXd> A(as<Map<MatrixXd> >(AA));
// evaluate and columnwise maximum entry of A
const MatrixXd Amax(A.colwise().maxCoeff());
return wrap(Amax);
'
rcppeigen_max_over_columns <- cxxfunction(signature(AA = "matrix"), maxOverColCpp, plugin = "RcppEigen")
然后,为了更改该函数以将其包含在现有的 R 包中,我重写了代码,如下所示,将其保存在rcppeigen_max_over_columns.cpp
在一个新的src
现有 R 包中的文件夹:
// we only include RcppEigen.h which pulls Rcpp.h in for us
#include <RcppEigen.h>
// via the depends attribute we tell Rcpp to create hooks for
// RcppEigen so that the build process will know what to do
//
// [[Rcpp::depends(RcppEigen)]]
// via the exports attribute we tell Rcpp to make this function
// available from R
//
// [[Rcpp::export]]
Eigen::MatrixXd rcppeigen_max_over_columns(const Eigen::MatrixXd & A){
Eigen::MatrixXd Amax = A.colwise().maxCoeff();
return Amax;
}
(事实上,它有点长,因为我还需要找到行数的最大值。)
Then:
-
用以下行修改了描述文件:
导入:Rcpp (>= 0.11.3)、RcppEigen (>= 0.3.2.2.0)
链接到:Rcpp、RcppEigen
-
使用以下行修改 NAMESPACE 文件:
useDynLib(toyRpackage)
导入(RcppEigen)
importFrom(Rcpp, evalCpp)
-
在 R 终端中,输入以下内容,我认为它粘合了 R 和 C++:
Rcpp::compileAttributes(pkgdir="toyRpackage", verbose=getOption("verbose"))
然后对于普通包裹,我做了R CMD check
and R CMD build
.
第一个问题是将 RcppEigen 函数包含到现有 R 包中的过程是否正确? (我完全忽略了任何Makevars
文件或任何.h
文件——我真的不知道它们是做什么的...也不太理解对 NAMESPACE 文件的更改。我尝试复制RcppEigen.package.skeleteon()
设置,但我将我的功能添加到现有的包中。所以最好知道是否可以,以防万一我错过了一些以后可能会出现问题的东西。)
第二个问题是我是否需要某个地方的“地图”rcppeigen_max_over_columns.cpp
这样当矩阵从 R 传递到 C++ 时就不会被复制?
我知道这是一个初学者问题,但我在理解 .cpp 文件中的语法时遇到了一些困难,因为我不懂 C++。我想也许这个问题可能会帮助其他也尝试向其包中添加简单功能的人。 :)
另外,如果您对使用 RcppEigen 而不是 RcppArmadillo 有任何强烈的感受,请告诉我。我读http://thread.gmane.org/gmane.comp.lang.r.rcpp/3522 http://thread.gmane.org/gmane.comp.lang.r.rcpp/3522这很有用。对于我在列上取最大值的示例,RcppEigen 似乎更快,不知道为什么。