Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scope

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?

like image 523
Leo Avatar asked Sep 01 '11 19:09

Leo


People also ask

Can we create restricted scope variable in JavaScript?

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.

What is the scope of a script variable?

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.

What determines the scope of a variable?

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.


2 Answers

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.

like image 111
Joshua Ulrich Avatar answered Sep 28 '22 00:09

Joshua Ulrich


You can use the local function.

like image 32
Greg Snow Avatar answered Sep 28 '22 02:09

Greg Snow