Wart Wart - 3 years ago 83
R Question

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

If I type
, this will work, but when I'm making my own package, I like to use
when referencing things from other packages. I can't do
as new is not a function from the Matrix package.

Answer Source

You can use the getClassDef function to get a class definition from a specific package and then call new() on that. 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download