【问题标题】:Make sure that R functions don't use global variables确保 R 函数不使用全局变量
【发布时间】: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 是否可以自行检测,而无需手动扫描我的整个代码。

标签: r function workspace


【解决方案1】:

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

【讨论】:

  • 这是一个很好的起点,我找到了解决问题的方法。我将其编辑到我的帖子中。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 2014-04-20
    • 1970-01-01
    相关资源
    最近更新 更多