如何从 Rcpp 代码中的 R 包创建 S4 类的实例 [英] How to create instances of S4 classes from R packages in Rcpp code

查看:38
本文介绍了如何从 Rcpp 代码中的 R 包创建 S4 类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rcpp 试图从 Rcpp 代码中创建一个 sparseMatrix 的实例,让我不知所措.

I'm getting my feet wet with Rcpp trying to create an instance of a sparseMatrix from within Rcpp code.

我知道为了创建 S4 对象,我们使用所需类的名称作为字符串调用 S4 构造函数,例如:

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

我认为这是因为尚未加载 Matrix 包?我试过添加

I assume this is because the Matrix package has not been loaded? I have tried adding

// [[Rcpp::depends(Matrix)]]

以及包的说明中 Matrix 的 Imports 和 LinkingTo 指令,但我仍然遇到相同的错误.如何从 Rcpp 中的 R 类创建实例?

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?

更新:关注 coatless' 答案,如果不加载 Matrix,则需要在命名空间中导入类:

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

如果您使用 Roxygen2 来管理命名空间,请照顾它.

Takes care of it in case you are using Roxygen2 to manage the namespace.

推荐答案

您遇到的问题是 Matrix 包尚未加载.因此,当 Rcpp 搜索 dgCMatrix ctor 时,它会出现空的,从而触发您看到的错误.为了解决这个问题,您可以在每个会话开始时简单地加载一次 Matrix 库.例如

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

或者,您可以在正在执行的 sourceCpp 编译中添加加载调用.这有点极端,因为您只需要加载一次库.

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.

不过,以下内容应该始终适用于 sourceCpp()

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()
*/

当您将其移动到 R 包中时,请确保在 DESCRIPTION

When you move this into an R package, make sure you import the Matrix package in the DESCRIPTION

Imports:
    Matrix

并在NAMESPACE中导入dgCMatrix定义.

importClassesFrom(Matrix, dgCMatrix)

这篇关于如何从 Rcpp 代码中的 R 包创建 S4 类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆