Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
545 views
in Technique[技术] by (71.8m points)

how to access global/outer scope variable from R apply function?

I can't seem to make apply function access/modify a variable that is declared outside... what gives?

    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
", 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
", i))
        i
    }

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

Results:

    age=11, weight=100
    age=12, weight=105
    age=13, weight=110
    i=0
    y=0, z=0
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using the <<- operator you can write to variables in outer scopes:

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
", 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
", i))
    i
}

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

The result here:

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

Note that the usage of <<- is dangerous, as you break up scoping. Do this only if really necessary and if you do, document that behavior clearly (at least in bigger scripts)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...