How do you determine the namespace of a function?

后端 未结 5 540
予麋鹿
予麋鹿 2020-11-30 05:48

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

5条回答
  •  北海茫月
    2020-11-30 06:08

    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"
    

提交回复
热议问题