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

时间:2023-01-24 14:52:52

I'm writing some code in R and have around 600 lines of functions right now and want to know if there is an easy way to check, if any of my functions is using global variables (which I DON'T want).

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

For example it could give me an error if sourcing this code:

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

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!  

Solution to the problem with the help of @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
}

Results will look like this:

> which_global
$arrange_vars
character(0)

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

$create_Flood_CuRve
[1] "y"

$dens_GEV
character(0)
...

2 个解决方案

#1


2  

For a given function like example_function, you can use package codetools:

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

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

To collect all functions see Is there a way to get a vector with the name of all functions that one could use in R?

要收集所有函数,请参阅是否有办法获得一个可以在R中使用的所有函数名称的向量?

#2


0  

What about emptying your global environment and running the function? If an object from the global environment were to be used in the function, you would get an error, e.g.

如何清空您的全局环境并运行该功能?如果要在函数中使用来自全局环境的对象,则会出现错误,例如

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

#1


2  

For a given function like example_function, you can use package codetools:

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

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

To collect all functions see Is there a way to get a vector with the name of all functions that one could use in R?

要收集所有函数,请参阅是否有办法获得一个可以在R中使用的所有函数名称的向量?

#2


0  

What about emptying your global environment and running the function? If an object from the global environment were to be used in the function, you would get an error, e.g.

如何清空您的全局环境并运行该功能?如果要在函数中使用来自全局环境的对象,则会出现错误,例如

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