如何访问全局/外部范围的变量来自R应用功能?(how to access global/outer

2019-07-04 06:59发布

我似乎无法使应用功能访问/修改声明以外的变量...怎么办?

    x = data.frame(age=c(11,12,13), weight=c(100,105,110))
    x

    testme <- function(df) {
        i <- 0
        apply(df, 1, function(x) {
            age <- x[1]
            weight <- x[2]
            cat(sprintf("age=%d, weight=%d\n", age, weight))
            i <- i+1   #this could not access the i variable in outer scope
            z <- z+1   #this could not access the global variable
        })
        cat(sprintf("i=%d\n", i))
        i
    }

    z <- 0
    y <- testme(x)
    cat(sprintf("y=%d, z=%d\n", y, z))

结果:

    age=11, weight=100
    age=12, weight=105
    age=13, weight=110
    i=0
    y=0, z=0

Answer 1:

使用<<-运营商,你可以写在外部范围变量:

x = data.frame(age=c(11,12,13), weight=c(100,105,110))
x

testme <- function(df) {
    i <- 0
    apply(df, 1, function(x) {
        age <- x[1]
        weight <- x[2]
        cat(sprintf("age=%d, weight=%d\n", age, weight))
        i <<- i+1   #this could not access the i variable in outer scope
        z <<- z+1   #this could not access the global variable
    })
    cat(sprintf("i=%d\n", i))
    i
}

z <- 0
y <- testme(x)
cat(sprintf("y=%d, z=%d\n", y, z))

这里的结果:

age=11, weight=100
age=12, weight=105
age=13, weight=110
i=3
y=3, z=3

注意,使用<<-是危险的,因为你打破了作用域。 做到这一点只有在真正必要的,如果你这样做,清楚地记录该行为(至少在更大的脚本)



Answer 2:

里面试试你的应用如下。 与n的值实验。 我认为, i应该比少一个z

         assign("i", i+1, envir=parent.frame(n=2))
         assign("z", z+1, envir=parent.frame(n=3))



testme <- function(df) {
    i <- 0
    apply(df, 1, function(x) {
        age <- x[1]
        weight <- x[2]
        cat(sprintf("age=%d, weight=%d\n", age, weight))

        ## ADDED THESE LINES
         assign("i", i+1, envir=parent.frame(2))
         assign("z", z+1, envir=parent.frame(3))

    })
    cat(sprintf("i=%d\n", i))
    i
}

OUTPUT

> z <- 0
> y <- testme(x)
age=11, weight=100
age=12, weight=105
age=13, weight=110
i=3
> cat(sprintf("y=%d, z=%d\n", y, z))
y=3, z=3     


文章来源: how to access global/outer scope variable from R apply function?
标签: r scope apply