How to limit the scope of variables used in a script?

Say I wrote an R script that uses some variables. When I run it, these variables clutter up the global R environment. To prevent this, how to limit the scope of the variables used in a script to just that script? Note. I know that one of the ways is to use functions, are there other ways?

+7
source share
2 answers

Just use the local=TRUE argument for source and evaluate source somewhere other than your global environment. Here are some ways to do this (assuming you don't want to have access to variables in the script). foo.R contains only 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 direct solution.

 sys.source("c:/foo.R", envir=new.env()) 

You can also evaluate the file in a connected environment if you want to access variables. See the examples in ?sys.source for how to do this.

+10
source

You can use the local function.

+4
source

All Articles