Binding External Variables in R

Suppose I have the following function:

g = function(x) x+h

Now, if I have an object with a name in my environment h, I would not have a problem:

h = 4
g(2)

## should be 6

Now I have another function:

f = function() {
    h = 3
    g(2)
}

I would expect:

rm(h)
f()

## should be 5, isn't it?

Instead, I get an error message

## Error in g(2) : object 'h' not found

I would expect it to gbe evaluated in the environment f, so that hin fwill be attached to h in g, as it was when I performed gwithin .GlobalEnv. This does not happen (obviously). any explanation why? how to overcome this so that the function inside the function (for example g) is evaluated using the environment?

+6
source share
1 answer

() .

, . g R:

g = function(x) x+h

g . , g :

f = function() {
    h = 3
    g(2)
}

f. g, , , . h, f.

, g h, f, g f:

f = function() {
    h = 3
    g = function(x) x+h
    g(2)
}

g f ( , g g, R).

g :

f = function() {
    h = 3
    environment(g) <- environment()
    g(2)
}
+7

Source: https://habr.com/ru/post/1014720/


All Articles