Jon Claus
Jon Claus

Reputation: 2932

Creating R function with local variable using its value

I would like to create a function that uses a variable already defined such that when I change this variable, the functionality of the created function doesn't change. Normally, when you use create a function in an environment using a variable defined in that said environment, the function will look up the value of the variable in that environment whenever it is called. For example:

> x = 3
> f = function() x + 3
> f()
[1] 6
> x = 4
> f()
[1] 7

I would like to create f such that it is simply the function 3 + 3 and always returns 6. Is there any easy way to do this in R? I know that I could manually assign the relevant parts of the function, i.e.

> body(f)[[2]] = x
> f
function () 
4 + 3

This strategy is quite tedious though, as it requires you to manually go through and change all occurrences. Is there an easier way?

Upvotes: 0

Views: 33

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

Copy the value to a local variable:

f = local({
    x = x
    function () x + 3
})

f()
# [1] 6
x = 4
f()
# [1] 3

Now f is defined inside its own environment that contains the cached value of x:

ls(environment(f))
# [1] "x"
environment(f)$x
# [1] 3

Upvotes: 3

Related Questions