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?
You can't restrict the scope of a Function using the "call" or "apply" methods, but you can use a simple trick using "eval" and scoping to essentially hide any specific global variables from the function to be called.
Script: This is the scope created when you run a script. Variables defined in the script are only available to the script scope and not the global or parent scope. Local: This is the current scope of where a command or script is currently running.
In simple terms, scope of a variable is its lifetime in the program. This means that the scope of a variable is the block of code in the entire program where the variable is declared, used, and can be modified.
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.
You can use the local
function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With