[Rd] pinning down symbol values (Scoping/Promises) question

Ross Boylan ross at biostat.ucsf.edu
Fri Feb 16 22:30:43 CET 2007


I would like to define a function using symbols, but freeze the symbols
at their current values at the time of definition.  Both symbols
referring to the global scope and symbols referring to arguments are at
issue. Consider this (R 2.4.0):
> k1 <- 5
> k
[1] 100
> a <- function(z) function() z+k
> a1 <- a(k1)
> k1 <- 2
> k <- 3
> a1()
[1] 5
> k <- 10
> k1 <- 100
> a1()
[1] 12

First, I'm a little surprised that that the value for k1 seems to get
pinned by the initial evaluation of a1.  I expected the final value to
be 110 because the z in z+k is a promise.

Second, how do I pin the values to the ones that obtain when the
different functions are invoked?  In other words, how should a be
defined so that a1() gets me 5+100 in the previous example?

I have a partial solution (for k), but it's ugly.  With k = 1 and k1 =
100,
> a <- eval(substitute(function(z) function() z+x, list(x=k)))
> k <- 20
> a1 <- a(k1)
> a1()
[1] 101
(by the way, I thought a <- eval(substitute(function(z) function() z+k))
would work, but it didn't).

This seems to pin the passed in argument as well, though it's even
uglier:
> a <- eval(substitute(function(z) { z; function() z+x}, list(x=k)))
> a1 <- a(k1)
> k1 <- 5
> a1()
[1] 120

-- 
Ross Boylan                                      wk:  (415) 514-8146
185 Berry St #5700                               ross at biostat.ucsf.edu
Dept of Epidemiology and Biostatistics           fax: (415) 514-8150
University of California, San Francisco
San Francisco, CA 94107-1739                     hm:  (415) 550-1062



More information about the R-devel mailing list