
60 R Programming for Bioinformatics
> foo = function() {
+ y = 10
+ function(x) x + y
+ }
> bar = foo()
> bar
function (x)
x + y
<environment: 0x2d3c580>
> is.function(bar)
[1] TRUE
> bar(3)
[1] 13
Functions, such as foo in the preceding example, that have an enclosing
environment are often referred to as closures. A closure can either be created,
as in that example, by the explicit creation of a function in an environment
other than the global environment or they can be created explicitly by at-
taching an environment to a function using env = and then populating that
environment, as is shown in the next example.
> bar2 = function(x) x + z
> e1 = new.env()
> e1$z ...