1
这对我来说有点棘手,但请参阅下面的示例。我试图通过将脚本加载到函数中来隔离一些R脚本的范围。但是,加载“嵌套”函数时这不起作用。下面的示例中,函数'inside'可以在加载后调用,但是'outside'函数错误地指出它无法在内部找到函数。R错误:从文件加载时找不到函数
#this would be in some file
inside <- function(a, b){
return(a+b)
}
outside <- function(c, d){
inside(c, d)
}
save.image("my_r_functions.model")
rm(list = ls())
#this would be in some other file
wrapper <- function(d, e){
load("my_r_functions.model")
print(paste('inside works: ', inside(d,e)))
print('but outside can not find inside')
outside(d,e)
}
wrapper(1,2)
输出:
[1] "inside works: 3"
[1] "but outside can not find inside"
Error in outside(d, e) : could not find function "inside"
谢谢,我怎么可以指定环境是包装函数里面?我不希望全球范围内存在“内部”和“外部”功能。你可以直接调用outside()而不用调用wrapper().... – mgcdanny 2015-04-03 15:06:13
environment(wrapper)是你的函数环境,我在上面编辑了我的答案,所以它保留在函数 – jeborsel 2015-04-03 15:14:15
非常感谢! – mgcdanny 2015-04-03 15:15:19