在 R 中编写函数,牢记作用域 [英] Writing functions in R, keeping scoping in mind

查看:36
本文介绍了在 R 中编写函数,牢记作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常编写需要查看环境中其他对象的函数.例如:

I often write functions that need to see other objects in my environment. For example:

> a <- 3
> b <- 3
> x <- 1:5
> fn1 <- function(x,a,b) a+b+x
> fn2 <- function(x) a+b+x
> fn1(x,a,b)
[1]  7  8  9 10 11
> fn2(x)
[1]  7  8  9 10 11

正如预期的那样,这两个函数是相同的,因为 fn2 在执行时可以看到"a 和 b.但是每当我开始利用这一点时,在大约 30 分钟内,我最终会在没有任何必要变量(例如 a 或 b)的情况下调用该函数.如果我不利用这一点,那么我会觉得我在不必要地传递对象.

As expected, both these functions are identical because fn2 can "see" a and b when it executes. But whenever I start to take advantage of this, within about 30 minutes I end up calling the function without one of the necessary variables (e.g. a or b). If I don't take advantage of this, then I feel like I am passing around objects unnecessarily.

明确说明函数需要什么更好吗?还是应该通过内联注释或函数的其他文档来处理?有没有更好的办法?

Is it better to be explicit about what a function requires? Or should this be taken care of via inline comments or other documentation of the function? Is there a better way?

推荐答案

如果我知道我将需要一个由一些值参数化并重复调用的函数,我会通过使用闭包来避免全局变量:

If I know that I'm going to need a function parametrized by some values and called repeatedly, I avoid globals by using a closure:

make.fn2 <- function(a, b) {
    fn2 <- function(x) {
        return( x + a + b )
    }
    return( fn2 )
}

a <- 2; b <- 3
fn2.1 <- make.fn2(a, b)
fn2.1(3)    # 8
fn2.1(4)    # 9

a <- 4
fn2.2 <- make.fn2(a, b)
fn2.2(3)    # 10
fn2.1(3)    # 8

这巧妙地避免了引用全局变量,而是将函数的封闭环境用于 a 和 b.调用 fn2 实例时,修改全局变量 a 和 b 不会导致意外的副作用.

This neatly avoids referencing global variables, instead using the enclosing environment of the function for a and b. Modification of globals a and b doesn't lead to unintended side effects when fn2 instances are called.

这篇关于在 R 中编写函数,牢记作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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