R 强制本地范围 [英] R force local scope

查看:46
本文介绍了R 强制本地范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能不是正确的术语,但希望我能明白我的意思.

This is probably not correct terminology, but hopefully I can get my point across.

我经常做这样的事情:

myVar = 1
f <- function(myvar) { return(myVar); }
# f(2) = 1 now

R 愉快地使用了函数范围之外的变量,这让我摸不着头脑,想知道我怎么可能得到我现在的结果.

R happily uses the variable outside of the function's scope, which leaves me scratching my head, wondering how I could possibly be getting the results I am.

是否有任何选项说强制我只使用以前在此函数范围内分配过值的变量"?例如,Perl 的 use strict 就是这样做的.但我不知道 R 有等价于 my.

Is there any option which says "force me to only use variables which have previously been assigned values in this function's scope"? Perl's use strict does something like this, for example. But I don't know that R has an equivalent of my.

谢谢,我知道我以不同的方式将它们大写.确实,这个例子是专门为了说明这个问题而创建的!

Thank you, I am aware of that I capitalized them differently. Indeed, the example was created specifically to illustrate this problem!

我想知道当我这样做时,是否有一种方法可以让 R 自动警告我.

I want to know if there is a way that R can automatically warn me when I do this.

编辑 2:此外,如果 Rkward 或其他 IDE 提供此功能,我也想知道.

EDIT 2: Also, if Rkward or another IDE offers this functionality I'd like to know that too.

推荐答案

据我所知,R 不提供严格使用"模式.所以你有两个选择:

As far as I know, R does not provide a "use strict" mode. So you are left with two options:

1 - 确保所有严格"函数都没有 globalenv 作为环境.您可以为此定义一个很好的包装函数,但最简单的是调用 local:

1 - Ensure all your "strict" functions don't have globalenv as environment. You could define a nice wrapper function for this, but the simplest is to call local:

# Use "local" directly to control the function environment
f <- local( function(myvar) { return(myVar); }, as.environment(2))
f(3) # Error in f(3) : object 'myVar' not found

# Create a wrapper function "strict" to do it for you...
strict <- function(f, pos=2) eval(substitute(f), as.environment(pos))
f <- strict( function(myvar) { return(myVar); } )
f(3) # Error in f(3) : object 'myVar' not found

2 - 进行代码分析,警告您不良"用法.

2 - Do a code analysis that warns you of "bad" usage.

这是一个checkStrict 函数,希望它可以满足您的需求.它使用了优秀的 codetools 包.

Here's a function checkStrict that hopefully does what you want. It uses the excellent codetools package.

# Checks a function for use of global variables
# Returns TRUE if ok, FALSE if globals were found.
checkStrict <- function(f, silent=FALSE) {
    vars <- codetools::findGlobals(f)
    found <- !vapply(vars, exists, logical(1), envir=as.environment(2))
    if (!silent && any(found)) {
        warning("global variables used: ", paste(names(found)[found], collapse=', '))
        return(invisible(FALSE))
    }

    !any(found)
}

并尝试一下:

> myVar = 1
> f <- function(myvar) { return(myVar); }
> checkStrict(f)
Warning message:
In checkStrict(f) : global variables used: myVar

这篇关于R 强制本地范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆