5

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?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Marcin Możejko
  • 39,542
  • 10
  • 109
  • 120
  • 1
    [This post](http://stackoverflow.com/questions/10904124/global-and-local-variables-in-r) should help. – LPs May 02 '16 at 12:27

1 Answers1

3

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
gsamaras
  • 71,951
  • 46
  • 188
  • 305
Roland
  • 127,288
  • 10
  • 191
  • 288