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

时间:2018-03-16 10:12:05

标签: r function workspace

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

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

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

2 个答案:

答案 0 :(得分:2)

对于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?

答案 1 :(得分: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
相关问题