如何限制脚本中使用的变量的范围?

时间:2022-03-09 23:35:53

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?

假设我写了一个使用一些变量的R脚本。当我运行它时,这些变量使全局R环境变得混乱。为了防止这种情况,我如何仅将脚本中使用的变量范围限制为该脚本?注意:我知道一种方法是使用函数,还有其他方法吗?

2 个解决方案

#1


10  

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).

只需使用local = TRUE参数来源和评估除全局环境之外的其他地方的源。以下是一些方法(假设您不希望能够访问脚本中的变量)。 foo.R只包含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可能是最直接的解决方案。

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.

如果要访问变量,还可以在附加环境中评估文件。有关如何执行此操作,请参阅?sys.source中的示例。

#2


4  

You can use the local function.

您可以使用本地功能。

#1


10  

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).

只需使用local = TRUE参数来源和评估除全局环境之外的其他地方的源。以下是一些方法(假设您不希望能够访问脚本中的变量)。 foo.R只包含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可能是最直接的解决方案。

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.

如果要访问变量,还可以在附加环境中评估文件。有关如何执行此操作,请参阅?sys.source中的示例。

#2


4  

You can use the local function.

您可以使用本地功能。