我可以在 运行 自定义函数后阻止子函数返回 R 环境吗?

Can I prevent subfunctions from returning to R environment after running custom function?

设置:

假设我有两个 R 函数,x()y()

# Defining function x 
# Simple, but what it does is not really important.
x <- function(input)
{output <- input * 10
  return(output)}

x() 包含在一个 .R 文件中,并存储在与 y() 相同的目录中,但在不同的文件中。

# Defining function y; 
# What's important is that Function y's output depends on function x
y <- function(variable){
  source('x.R')
  output <- x(input = variable)/0.5
    return(output)
}

当在 R 中定义 y() 时,环境仅填充 y(),如下所示:

然而,我们实际上运行 y()...

# Demonstrating that it works
> y(100)
[1] 2000

环境中也填充了 x,如下所示:

问题:

我可以在 y 中添加代码以防止 x 在我构建 运行 之后填充 R 环境吗?一个依赖于几个源文件的函数,我不想在函数具有 运行 后保留在环境中。我想避免在人们使用主要功能时不必要地拥挤 R 环境,但是添加一个简单的 rm(SubFunctionName) 并没有奏效,而且我还没有找到关于该主题的任何其他线程。有任何想法吗?感谢您的宝贵时间!

1)source 行替换为以下内容,使其成为本地环境的来源。

source('x.R', local = TRUE)

2) 另一种可能性是这样写 y 这样 x.R 只在 y.R 被获取时才被读取而不是每个调用时间 y

y <- local({
  source('x.R', local = TRUE)
  function(variable) x(input = variable) / 0.5
})

3) 如果你不介意在 y.R 中定义 x 那么 y.R 可以这样写。请注意,这消除了在代码中分隔文件处理和代码的任何 source 语句。

y <- function(variable) {
  x <- function(input) input * 10
  x(input = variable) / 0.5
}

4) 另一种分离文件处理和代码的可能性是从 y 中删除 source 语句并读取 x.Ry.R 进入同一本地环境,以便在 e 之外只能通过 e 访问它们。在这种情况下,可以通过删除 e.

来删除它们
e <- local({
  source("x.R", local = TRUE)
  source("y.R", local = TRUE)
  environment()
})

# test
ls(e)
## [1] "x" "y"
e$y(3)
## [1] 60

4a) 具有类似优点但更短的变体是:

e <- new.env()
source("x.R", local = e)
source("y.R", local = e)

# test
ls(e)
## [1] "x" "y"
e$y(3)
## [1] 60

5) 另一种方法是使用 CRAN 模块包或其 README 中引用的 klmr/modules 包。