确保 R 函数不使用全局变量

Make sure that R functions don't use global variables

我正在用 R 编写一些代码,现在有大约 600 行函数,想知道是否有一种简单的方法来检查我的函数是否正在使用全局变量(我不想要)。

例如,如果采购此代码,它可能会给我一个错误:

example_fun<-function(x){
  y=x*c
  return(y)
}

x=2
c=2
y=example_fun(x)

WARNING: Variable c is accessed from global workspace!  

在@Hugh的帮助下解决问题:

install.packages("codetools")
library("codetools")

x = as.character(lsf.str())

which_global=list()

for (i in 1:length(x)){
  which_global[[x[i]]] = codetools::findGlobals(get(x[i]), merge = FALSE)$variables
}

结果将如下所示:

> which_global
$arrange_vars
character(0)

$cal_flood_curve
[1] "..count.." "FI"        "FI_new"   

$create_Flood_CuRve
[1] "y"

$dens_GEV
character(0)
...

清空全局环境和 运行 函数怎么样?如果要在函数中使用来自全局环境的对象,则会出现错误,例如

V <- 100
my.fct <- function(x){return(x*V)}
> my.fct(1)
[1] 100
#### clearing global environment & re-running my.fct <- function... ####
> my.fct(1)
Error in my.fct(1) : object 'V' not found

对于像 example_function 这样的给定函数,您可以使用包 codetools:

codetools::findGlobals(example_fun, merge = FALSE)$variables
#> [1] "c"

要收集所有函数,请参阅 Is there a way to get a vector with the name of all functions that one could use in R?