R函数中的可变范围 [英] variable-scope in R functions

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

问题描述

我想以灵活的方式指定函数.在紧随其后创建另一个函数时,如何确保给定函数的环境不变.

I'd like to specify functions in a flexible way. How can I make sure that the environment of a given function does not change when I create another function just after it.

为了说明这一点,它可以正常工作:

To illustrate, this works properly:

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

这不是

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

a <- 2; b <- 3
fn2.1 <- make.fn2(a, b)

a <- 4
fn2.2 <- make.fn2(a, b)

fn2.1(3)    # 10
fn2.1(4)    # 11
fn2.2(3)    # 10
fn2.1(3)    # 10

推荐答案

这是由于延迟评估造成的.该函数直到被调用才真正构建.因此,在第二种情况下,两次都选择了新版本的a.另请参见其他问题.

This is due to lazy evaluation. The function is not actually constructed until it is called. So, in the second case, both times the new version of a is picked up. See also this other question.

您可以使用force解决此问题:

You can solve this issue by using force:

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

这将在创建函数时(而不是在调用函数时)强制函数选择ab的值.它会产生正确的输出:

This forces the function to pick up the values of a and b when the function is created, not when the function is called. It produces the correct output:

> a <- 2; b <- 3
> fn2.1 <- make.fn2(a, b)
> 
> a <- 4
> fn2.2 <- make.fn2(a, b)
> 
> fn2.1(3)    # 10
[1] 8
> fn2.1(4)    # 11
[1] 9
> fn2.2(3)    # 10
[1] 10
> fn2.1(3)    # 10
[1] 8
> 

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

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