简体   繁体   English

R函数中的变量范围

[英]variable-scope in R functions

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

This does not 事实并非如此

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

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. 因此,在第二种情况下,两次都会获取新版本的a See also this other question . 另见其他问题

You can solve this issue by using force : 您可以使用force来解决此问题:

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

This forces the function to pick up the values of a and b when the function is created, not when the function is called. 这会强制函数在创建函数时获取ab的值,而不是在调用函数时。 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
> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM