Skip to content

Instantly share code, notes, and snippets.

@artemklevtsov
Last active January 24, 2016 06:53
Show Gist options
  • Save artemklevtsov/c2462f3c8606a3756ace to your computer and use it in GitHub Desktop.
Save artemklevtsov/c2462f3c8606a3756ace to your computer and use it in GitHub Desktop.
Find an object environment name
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))]
}
# returns only a first found result
getEnvName2 <- function(f) {
envs <- c(.GlobalEnv, lapply(loadedNamespaces(), .getNamespace))
for (env in envs) {
if (exists(f, env, mode = "function", inherits = FALSE))
return(environmentName(env))
}
return(NA)
}
@artemklevtsov
Copy link
Author

Example:

median <- function() {}
getEnvName("median")
#> [1] "R_GlobalEnv" "stats"
getEnvName2("median")
#> [1] "R_GlobalEnv"
getEnvName(".try_quietly")
#> [1] "tools"
getEnvName("getEnvName")
#> [1] "R_GlobalEnv"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment