Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scope

r

apply

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\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)) 

Results:

    age=11, weight=100     age=12, weight=105     age=13, weight=110     i=0     y=0, z=0 
like image 491
fatdragon Avatar asked Nov 30 '12 06:11

fatdragon


People also ask

Can R function access global variable?

As the name suggests, Global Variables can be accessed from any part of the program.

How do you access global variables?

Global Variable: The variable that exists outside of all functions. It is the variable that is visible from all other scopes. We can access global variable if there is a local variable with same name in C and C++ through Extern and Scope resolution operator respectively.

How do you access local variables outside the scope?

Local variables cannot be accessed outside the function declaration. Global variable and local variable can have same name without affecting each other.

Can global variables be accessed anywhere?

Variables that are created outside of a function are known as Global Variables . A global variable is one that can be accessed anywhere . This means, global variable can be accessed inside or outside of the function.


1 Answers

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\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)) 

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)

like image 71
Thilo Avatar answered Sep 17 '22 20:09

Thilo