[英]How do I call the new function in R when the object is defined in another package?
Suppose I'm creating a package and I'd like to define a function that creates an object where the object is defined in another package. 假设我正在创建一个包,我想定义一个函数来创建一个对象,在该对象中,对象在另一个包中定义。
For example: get_empty_mtx <- function() return(new("dgCMatrix"))
例如:
get_empty_mtx <- function() return(new("dgCMatrix"))
If I type library(Matrix)
, this will work, but when I'm making my own package, I like to use ::
when referencing things from other packages. 如果我输入
library(Matrix)
,这将有效,但是当我创建自己的包时,我喜欢在引用其他包时使用::
。 I can't do Matrix::new("dgCMatrix")
as new is not a function from the Matrix package. 我不能做
Matrix::new("dgCMatrix")
因为new不是Matrix包中的函数。
You can use the getClassDef
function to get a class definition from a specific package and then call new()
on that. 您可以使用
getClassDef
函数从特定包中获取类定义,然后在其上调用new()
。 For example 例如
new(getClassDef("dgCMatrix", getNamespace("Matrix")))
and new(getClassDef("dgCMatrix", "Matrix"))
also seems to work despite the documtation saying where
should be an environment. 和
new(getClassDef("dgCMatrix", "Matrix"))
似乎也尽管documtation说工作的where
应该是一个环境。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.