Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is scoping done in R

Tags:

c

scope

r

nested

Both R and C have lexical scope. So assuming that global scope is empty, in C the following code would not work :

int aux(int arg) {
   if (arg > 0) {
      int result = 1;
   } else {
      int result = 0;
   }
   return result;
 }

While in R the following code :

aux <- function(arg) {
   if (arg > 0) {
      result = 1
   } else {
      result = 0
   }
   return(result)
 }

Works properly. Can someone tell me what is the difference in scoping between R and C which makes these two functions behave differently?

like image 640
Marcin Możejko Avatar asked Oct 19 '22 10:10

Marcin Możejko


1 Answers

In R, the expression after the if condition is evaluated in the enclosing environment:

if (TRUE) environment()
#<environment: R_GlobalEnv>

(Surprisingly, I couldn't find documentation regarding this.)


You can change that by using local:

aux <- function(arg) {
  if (arg > 0) {
    local({result <- 1})
  } else {
    local({result <- 0})
  }
  return(result)
}

aux(1)
#Error in aux(1) : object 'result' not found
like image 153
Roland Avatar answered Oct 21 '22 07:10

Roland