R:源个人脚本隐藏了某些功能 [英] R: Source personal scripts keeping some functions hidden
问题描述
按照此
我想在给定的环境中(例如在sys.source
中)获取脚本,但是仅导出"某些功能而将其他功能保持私有"状态.
I want to source scripts inside a given environment, like in sys.source
, but "exporting" only some functions and keeping the others private.
我创建了此功能:
source2=function(script){
ps=paste0(script, "_")
assign(ps, new.env(parent=baseenv()))
assign(script, new.env(parent=get(ps)))
private=function(f){
fn=deparse(substitute(f))
assign(fn, f, parent.env(parent.frame()))
rm(list=fn, envir=parent.frame())
}
assign("private", private, get(script))
sys.source(paste0(script, ".R"), envir=get(script))
rm(private, envir=get(script))
attach(get(script), name=script)
}
在大多数情况下,此功能可以正常工作.
考虑脚本:
For the most part, this function works as expected.
Consider the script:
## foo.R
f=function() g()
g=function() print('hello')
private(g)
请注意private()
函数,该函数将隐藏g()
.
Note the private()
function, which will hide g()
.
如果可以的话,导入模块 foo
:
source2("foo")
source2("foo")
搜索路径中有一个新环境:
I have a new environment in the search path:
search()
## [1] ".GlobalEnv" "foo" "package:stats"
## [4] "package:graphics" "package:grDevices" "package:utils"
## [7] "package:datasets" "package:methods" "Autoloads"
## [10] "package:base"
当前环境.GlobalEnv
仅显示:
ls()
## [1] "source2"
但是如果我在foo
环境中列出项目:
But if I list items in foo
environment:
ls("foo")
## [1] "f"
因此,我可以运行:
f()
## [1] "hello"
问题在于g()
被完全隐藏了.
The problem is that g()
is hidden totally.
getAnywhere(g)
## no object named 'g' was found
太多了.实际上,如果我想调试f()
:
Too much. In fact, if I want to debug f()
:
debug(f)
f()
debugging in: f()
## Error in f() : could not find function "g"
问题是:
g()
在哪里?我还能取回吗?
The question is:
Where is g()
? Can I still retrieve it?
推荐答案
使用:
get("g",env=environment(f))
## function ()
## print("hello")
## <environment: 0x0000000018780c30>
ls(parent.env(environment(f)))
## [1] "g"
信贷请亚历山大·格里菲斯(Alexander Griffith)解决.
Credit goes to Alexander Griffith for the solution.
这篇关于R:源个人脚本隐藏了某些功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!