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?