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?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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
is probably the most straight-forward solution.
sys.source("c:/foo.R", envir=new.env())
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.
回答2:
You can use the local
function.