如何限制脚本中使用的变量的范围? [英] How to limit the scope of the variables used in a script?
问题描述
假设我编写了一个使用一些变量的 R 脚本.当我运行它时,这些变量会干扰全局 R 环境.为了防止这种情况,我如何将脚本中使用的变量范围限制为该脚本?注意:我知道一种方法是使用函数,还有其他方法吗?
Let's say I've written an R script which uses some variables. When I run it, those variables clutter the global R environment. To prevent this, how do I limit the scope of variables used in a script to that script only? Note: I know that one way is to use functions, are there any other ways?
推荐答案
只需将 local=TRUE
参数用于 source
并评估 source
除了您的全球环境之外的其他地方.这里有几种方法可以做到这一点(假设您不想访问脚本中的变量).foo.R
只包含 print(x <- 1:10)
.
Just use the local=TRUE
argument to source
and evaluate source
somewhere other than your global environment. Here are a few ways to do that (assuming you don't want to be able to access the variables in the script). foo.R
just contains print(x <- 1:10)
.
do.call(source, list(file="c:/foo.R", local=TRUE), envir=new.env())
# [1] 1 2 3 4 5 6 7 8 9 10
ls()
# character(0)
mysource <- function() source("c:/foo.R", local=TRUE)
mysource()
# [1] 1 2 3 4 5 6 7 8 9 10
ls()
# [1] "mysource"
sys.source
可能是最直接的解决方案.
sys.source
is probably the most straight-forward solution.
sys.source("c:/foo.R", envir=new.env())
您还可以在附加环境中评估文件,以防您想访问变量.有关如何执行此操作,请参阅 ?sys.source
中的示例.
You can also evaluate the file in an attached environment, in case you want to access the variables. See the examples in ?sys.source
for how to do this.
这篇关于如何限制脚本中使用的变量的范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!