Skip to content
Prev 80900 / 398502 Next

changing the value of a variable from inside a function

Use eval.parent as shown in example 1.  Note that you might
be tempted to use example 2 but it does not actually fulfill
the letter of the original post since it changes test in the lexical
environment of f, i.e.the environment where f is defined,
rather than the calling frame of f, i.e. the environment from where
f is called.  To get <<- to work with example 2 we must
create a new f that is the same as the original f but whose
lexical environment has been changed to be the caller frame
as shown in example 3.

# example 1.  ok.  test changed in caller frame.
test <- 11:13
f <- function(i) eval.parent(substitute(test[i] <- 99))
g <- function() { test <- 1:3; f(2); print(test) }
g()  # 1 99 3
test # 11 12 13

# example 2.  Same except f has been changed.
# Note that this changes test in the lexical environment
# rather than in the caller frame.
test <- 11:13
f <- function(i) test[i] <<- 99
g <- function() { test <- 1:3; f(2); print(test) }
g()  # 1 2 3
test  # 11 99 13

# example 3. same as example 2 but the lexical environment of f is
# forced to be the caller frame so that it works as in example 1.
# f is the same as in example 1 and g has been changed to
# create a new f like the original f but with the caller frame as its
# lexical environment.
test <- 11:13
f <- function(i) test[i] <<- 99
g <- function() { test <- 1:3; environment(f) <- environment(); f(2);
print(test) }
g()  # 1 99 3
test # 11 12 13


Another possibility, which is similar in effect to example 1, would be
to use defmacro in package gtools.
On 11/15/05, Michael Wolosin <msw10 at duke.edu> wrote: