Calling a function from a namespace
Asked Answered
C

2

31

I'm trying to alter the functionality of a few commands in a package in R. It's easy enough to see the source of the commands. However the function calls other functions that are in the package namespace. These functions are not exported objects. So how can I access them?

Specific example:

How would I access the asCall() function that is used in copula::rmvdc?

require(copula)
copula::rmvdc
getAnywhere("asCall")

so as.Call() exists in the copula package, but how do I access it?

> copula::asCall
Error: 'asCall' is not an exported object from 'namespace:copula'
Coleman answered 29/1, 2010 at 21:39 Comment(0)
M
69

Try this:

copula:::asCall

This was previously answered on R-help. That function was not exported in the package namespace, so you need to use the ::: operator instead. Typically functions are not exported when they are not intended for general usage (e.g. you don't need to document them in this case).

Mazel answered 29/1, 2010 at 21:48 Comment(1)
I can't believe it... I tried copula:asCall then copula::asCall and then said "well hellifiknow"Coleman
N
15

When developing, ?assignInNamespace is very useful.

This allows you to inject a new copy of a non-exported function into a package's namespace.

It would be nice if R's error message was more helpful. Instead of:

Error: 'matrixToPaths' is not an exported object from 'namespace:OpenMx'

Why not add:

You might try OpenMx:::matrixToPaths"
Nicolas answered 6/2, 2012 at 17:58 Comment(3)
"why not add ..." because you're not supposed to access a package's private objects. That's why they're called "private". In fact, one could ask why the ::: operator even exists.Gromwell
::: alows you to do modifications to pkg functions that use internal objects, to fit your needs. Isn´t this the spirit of open source?Bozo
assignInNamespace make sense because the world isn't perfect. Maybe there's a bug in an internal function and you don't want to download the entire source code and recompile the package. You just want to change one parameter. Ironclad rules like that assume a level of perfection that most programmers do not have.Camise

© 2022 - 2024 — McMap. All rights reserved.