How do you determine the namespace of a function?
Given a function, how do you determine which namespace it has come from?
For example, if I type mean.default
at the command prompt, the output includes the fact that it is in the base package. I want to be able to do something like getNamespace(mean.default)
and have it return "base" (or the actual base environment).
There is a getNamespace
function but seems to only accept package names rather than function names.
print.function
uses internal code to retrieve the namespace. I got as far as browsing do_printfunction
in src/main/print.c
but then gave up.
Solution 1:
I very recently learned about find()
which seems to do just this.
R> find("ls")
[1] "package:base"
R> find("na.locf")
[1] "package:zoo"
Solution 2:
You want getNamespaceName
+ environment
:
getNamespaceName(environment(mean.default))
# [1] "base"
Solution 3:
findFunction
is another option and ?findFunction
says you should use it instead of find
with mode="function"
. The result of findFunction
is a list of the environment(s) where the visible versions of the function are located.
Solution 4:
This function searches functions in the loaded namespaces and global environment:
getEnvName <- function(f) {
attached <- c(environmentName(.GlobalEnv), loadedNamespaces())
envs <- c(.GlobalEnv, lapply(attached[-1], .getNamespace))
attached[vapply(envs, function(env) exists(f, env, inherits = FALSE), logical(1))]
}
median <- function() {}
getEnvName("median")
#> [1] "R_GlobalEnv" "stats"
getEnvName(".try_quietly")
#> [1] "tools"
getEnvName("getEnvName")
#> [1] "R_GlobalEnv"