问题
I'm getting my feet wet with Rcpp trying to create an instance of a sparseMatrix from within Rcpp code.
I understand that in order to create S4 objects we call the S4 constructor with the name of the desired class as a string, e.g.:
S4 foo() {
S4 s("dgCMatrix");
return s;
}
But in my case this fails with
Error in getClass("dgCMatrix") : “dgCMatrix” is not a defined class
I assume this is because the Matrix package has not been loaded? I have tried adding
// [[Rcpp::depends(Matrix)]]
as well as Imports and LinkingTo directives for Matrix in the package's DESCRIPTION, but I still get the same error. How can one create instances from R classes from within Rcpp?
UPDATE: following coatless' answer, classes need to be imported in the namespace if Matrix is not to be loaded:
//' @importClassesFrom Matrix dgCMatrix
// [[Rcpp::export]]
S4 foo() {
S4 s("dgCMatrix");
return s;
}
Takes care of it in case you are using Roxygen2 to manage the namespace.
回答1:
The issue that you are running into is the Matrix
package has not been loaded. So, when Rcpp searches for the dgCMatrix ctor it comes up empty and, thus, triggering the error you see. To get around this, you can simply load the Matrix
library once at the start of every session. e.g.
library("Matrix")
sourceCpp("path/to/S4_declaration.cpp")
Alternatively, you could add a load call in the sourceCpp
compile you are performing. This is a bit more extreme as you only need to load the library once.
Though, the following should always work under sourceCpp()
#include <Rcpp.h>
// [[Rcpp::export]]
Rcpp::S4 make_dgCMatrix() {
Rcpp::S4 s("dgCMatrix");
return s;
}
/*** R
library("Matrix")
make_dgCMatrix()
*/
When you move this into an R package, make sure you import the Matrix
package in the DESCRIPTION
Imports:
Matrix
and import dgCMatrix
definition in NAMESPACE
.
importClassesFrom(Matrix, dgCMatrix)
来源:https://stackoverflow.com/questions/44560198/how-to-create-instances-of-s4-classes-from-r-packages-in-rcpp-code