如何确定R语言中匿名函数内部调用函数的命名空间?
Nice question! Let's walk through how to get the namespace of functions called inside an anonymous function, since you've already got the hang of doing this for regular namespace functions.
First, a quick recap of the standard method
For named functions that belong to a package namespace, we can use environment() to grab their execution environment, then getNamespaceName() to extract the namespace label:
environment(mean) #> <environment: namespace:base> getNamespaceName(environment(mean)) #> [1] "base"
The anonymous function challenge
For your example anonymous function:
anon_f <- function(x) mean(x)
Its environment is indeed the global environment (where it was defined), so it doesn't have a package namespace of its own:
environment(anon_f) #> <environment: R_GlobalEnv>
To get the namespace of the mean() function it calls internally, we need to dig into the anonymous function's body and target the specific functions it references. Here are two reliable ways to do this:
Method 1: Directly parse the function body
We can use body() to pull out the code inside the anonymous function, then extract the called function object to apply our standard namespace logic:
# Extract the function being called in the body called_function <- body(anon_f)[[1]] # Get its namespace getNamespaceName(environment(called_function)) #> [1] "base"
This works well for simple, straightforward function bodies.
Method 2: Batch find global dependencies with codetools
If your anonymous function calls multiple external functions or has a complex body, use the codetools package to automatically detect all global functions it depends on. Then we can fetch their namespaces in bulk:
library(codetools) # Find all global functions used by the anonymous function global_deps <- findGlobals(anon_f, merge = FALSE)$functions # Get namespace for each dependency sapply(global_deps, function(func_name) { getNamespaceName(environment(get(func_name))) }) #> mean #> "base"
Note: If the anonymous function calls locally defined functions (not package-based global functions), this will return their local environment instead of a namespace—since only package-owned functions have formal namespaces.
内容的提问来源于stack exchange,提问作者Thomas K

