Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutating a variable in a closure [duplicate]

Tags:

scope

closures

r

I'm pretty new to R, but coming from Scheme—which is also lexically scoped and has closures—I would expect being able to mutate outer variables in a closure.

E.g., in

foo <- function() {
  s <- 100

  add <- function() {
    s <- s + 1
  }

  add()
  s
}

cat(foo(), "\n") # prints 100 and not 101

I would expect foo() to return 101, but it actually returns 100:

$ Rscript foo.R
100

I know that Python has the global keyword to declare scope of variables (doesn't work with this example, though). Does R need something similar?

What am I doing wrong?

Update

Ah, is the problem that in add I am creating a new, local variable s that shadows the outer s? If so, how can I mutate s without creating a local variable?

like image 216
csl Avatar asked Apr 26 '14 16:04

csl


Video Answer


1 Answers

Use the <<- operator for assignment in the add() function.

From ?"<<-":

The operators <<- and ->> are normally only used in functions, and cause a search to made through parent environments for an existing definition of the variable being assigned. If such a variable is found (and its binding is not locked) then its value is redefined, otherwise assignment takes place in the global environment. Note that their semantics differ from that in the S language, but are useful in conjunction with the scoping rules of R. See ‘The R Language Definition’ manual for further details and examples.

like image 113
gagolews Avatar answered Nov 10 '22 12:11

gagolews