Leo
Leo

Reputation: 1911

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

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?

Upvotes: 7

Views: 2988

Answers (2)

Joshua Ulrich
Joshua Ulrich

Reputation: 176648

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.

Upvotes: 12

Greg Snow
Greg Snow

Reputation: 49640

You can use the local function.

Upvotes: 4

Related Questions