dan
dan

Reputation: 6304

Rcpp function cannot be found by 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

Here's my cpp file:

// [[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);
}

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)
}

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"

and neither comes up when preceded by myUtils::

Looks like I'm missing something but I can't figure out what it is.

Help would be appreciated.

Upvotes: 4

Views: 3317

Answers (2)

Kamil Slowikowski
Kamil Slowikowski

Reputation: 4614

Dirk said:

add eigenMatMult to exports, either by hand or via a roxygen tag

We probably don't want to modify NAMESPACE by hand if it is generated by roxygen2:

# Generated by roxygen2: do not edit by hand

So, let's add a tag for roxygen2, so it knows to add our function automatically to the NAMESPACE file.

Your code example looks like this:

// [[Rcpp::export]]
SEXP eigenMatMult(Eigen::MatrixXd A, Eigen::MatrixXd B){
  Eigen::MatrixXd C = A * B;

  return Rcpp::wrap(C);
}

It should look like this instead (notice the line with //' @export):

//' @export
// [[Rcpp::export]]
SEXP eigenMatMult(Eigen::MatrixXd A, Eigen::MatrixXd B){
  Eigen::MatrixXd C = A * B;

  return Rcpp::wrap(C);
}

Upvotes: 2

Dirk is no longer here
Dirk is no longer here

Reputation: 368181

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

  • call via ::: ie myUtils:::eigenMatMult(A, A)
  • add eigenMatMult to exports, either by hand or via a roxygen tag

Upvotes: 6

Related Questions