在R中,我source()
用来加载一些函数:
source("functions.R")
Run Code Online (Sandbox Code Playgroud)
是否可以获取此文件中定义的所有功能的列表?作为函数名称。(也许source()
本身可以以某种方式返回它?)。
PS:最后的办法是source()
第二次调用local({ source(); })
,然后在ls()
内部和过滤器函数中进行调用,但这太复杂了-有没有更简单,更简洁的解决方案?
我认为最好的方法是将文件来源到临时环境中。在该环境中查询所有功能,然后将这些值复制到父环境。
my_source <- function(..., local=NULL) {
tmp <- new.env(parent=parent.frame())
source(..., local = tmp)
funs <- names(tmp)[unlist(eapply(tmp, is.function))]
for(x in names(tmp)) {
assign(x, tmp[[x]], envir = parent.frame())
}
list(functions=funs)
}
my_source("script.R")
Run Code Online (Sandbox Code Playgroud)
这有点笨拙,但您可以source
像这样查看调用前后对象的变化。
# optionally delete all variables
#rm(list=ls())
before <- ls()
cat("f1 <- function(){}\nf2 <- function(){}\n", file = 'define_function.R')
# defines these
#f1 <- function() {}
#f2 <- function() {}
source('define_function.R')
after <- ls()
changed <- setdiff(after, before)
changed_objects <- mget(changed, inherits = T)
changed_function <- do.call(rbind, lapply(changed_objects, is.function))
new_functions <- changed[changed_function]
new_functions
# [1] "f1" "f2"
Run Code Online (Sandbox Code Playgroud)