ThomasP85 ThomasP85 -4 years ago 192
R Question

Get namespace of function

I'm developing a package where I wish to add an edit history to an object. The package allows other packages to register functions for editing the object. I'm looking for a way to record the version of the package that registered the function that was used for the edit.

The question is: Given a function how do you get the package from where it was exported? My idea is to investigate its search path, but

only reports the search path for the current environment and thus not for a function, which is what I need.

Any pointers to other approaches is greatly appreciated.

The context for getting the package is this:

registerFunction <- function(fun) {
package <- getPackage(fun) ## This is what I need
version <- getPackageVersion(package)
register(fun, package, version)

Answer Source

You can use getAnywhere For example, if you're looking for the namespace for the stringr function str_locate you can do

# [1] "package:stringr"   "namespace:stringr"

This will work as long as stringr is "visible on the search path, registered as an S3 method or in a namespace but not exported."

The result is a named list, and you can see what's available from getAnywhere with names

# [1] "name"    "objs"    "where"   "visible" "dups"  
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download