【发布时间】:2018-03-16 10:12:04
【问题描述】:
我正在用 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)
...
【问题讨论】:
-
最好的方法是在函数参数中添加
c。 -
我不相信你的要求是可能的,它需要更改
R范围规则,这将是一种不同的语言或至少是R的派生词。跨度> -
@Flo.P 是的,我知道,但我想知道 R/R-Studio 是否可以自行检测,而无需手动扫描我的整个代码。