R无法找到Rcpp函数 [英] Rcpp function cannot be found by R
问题描述
我构建了一个 R
package
(称为 myUtils
),该文件在中使用了
遵循哈德利手册.我的 cpp
文件> RStudio cpp
文件位于 src
目录中,该目录是在运行以下代码后创建的: devtools :: use_rcpp()
,并且位于我的 R
目录中,我有一个名为 myUtils.R
的文件,其内容如下:
I built an R
package
(called myUtils
), which uses a cpp
file, in RStudio
following Hadley's manual. My cpp
file resides in the src
directory, created after running: devtools::use_rcpp()
, and under my R
directory I have a file called myUtils.R
, with these lines:
#' myUtils: A package with various functions for my analyses
#'
#'
#' @docType package
#' @name myUtils
#' @useDynLib myUtils
#' @importFrom Rcpp sourceCpp
NULL
这是我的 cpp
文件:
// [[Rcpp::depends(RcppArmadillo, RcppEigen)]]
#include <RcppArmadillo.h>
#include <RcppEigen.h>
using namespace Rcpp;
// [[Rcpp::export]]
SEXP armaMatMult(arma::mat A, arma::mat B){
arma::mat C = A * B;
return Rcpp::wrap(C);
}
// [[Rcpp::export]]
SEXP eigenMatMult(Eigen::MatrixXd A, Eigen::MatrixXd B){
Eigen::MatrixXd C = A * B;
return Rcpp::wrap(C);
}
然后我运行了 devtools :: document()
,该代码将 useDynLib(myUtils)
添加到了 NAMESPACE
文件中.然后,我运行 Build&重新加载
,成功完成,并在 R
目录中创建了 RccpExports.R
文件,并在其中包含 cpp
函数,例如:
I then ran devtools::document()
which added useDynLib(myUtils)
to the NAMESPACE
file. I then ran Build & Reload
, which finished successfully, and created the RccpExports.R
file in the R
directory, with the cpp
functions in it, for example:
eigenMatMult <- function(A, B) {
.Call('_myUtils_eigenMatMult', PACKAGE = 'myUtils', A, B)
}
然后我尝试测试 eigenMatMult
,但无法识别:
Then I tried to test eigenMatMult
but it's not recognized:
set.seed(1)
A <- matrix(rnorm(100), 10, 10)
> eigenMatMult(A=A,B=A)
Error: could not find function "eigenMatMult"
并且在以 myUtils ::
好像我错过了一些东西,但我不知道它是什么.
Looks like I'm missing something but I can't figure out what it is.
我们将不胜感激.
推荐答案
Rcpp Attributes机制本身并不向 NAMESPACE
文件中的export指令添加函数.我们的示例使用通配符导出所有内容.
The Rcpp Attributes mechanism does not by itself add functions to the export directive in the NAMESPACE
file. Our example uses a wildcard to export everything.
因此,如果您的功能不可见,请执行以下一项或两项操作
So if your function is not visible, do either or both of
- 通过
:::
调用,即myUtils ::: eigenMatMult(A,A)
- 通过手工或通过roxygen标签将
eigenMatMult
添加到导出中
- call via
:::
iemyUtils:::eigenMatMult(A, A)
- add
eigenMatMult
to exports, either by hand or via a roxygen tag
这篇关于R无法找到Rcpp函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!