`eval` using variable local to the function - r

Sourcing this code:
a <- F
f1 <- function() a
f2 <- function() {
a <- T
eval(f1())
}
and calling f2() will return FALSE.
How to modify the arguments for the eval so that f2() will return TRUE ?

You can do this:
a <- F
f1 <- function() a
f2 <- function() {
a <- T
environment(f1) <- new.env()
eval(f1())
}
f2()
# [1] TRUE
Though I wouldn't encourage it. What we've done here is changed the environment of f1 to be one which has for enclosure f2's environment, which means f1 will have access to f2s variables through "lexical" scoping (well, faux-lexical here b/c we short circuited it).
Generally, as Roman suggests, you should explicitly pass arguments to functions as otherwise you can quickly run into trouble.

Related

Why is this simple function not working?

I first defined new variable x, then created function that require x within its body (not as argument). See code below
x <- c(1,2,3)
f1 <- function() {
x^2
}
rm(x)
f2 <- function() {
x <- c(1,2,3)
f1()
}
f(2)
Error in f1() : object 'x' not found
When I removed x, and defined new function f2 that first define x and then execute f1, it shows objects x not found.
I just wanted to know why this is not working and how I can overcome this problem. I do not want x to be name as argument in f1.
Please provide appropriate title because I do not know what kind of problem is this.
You could use a closure to make an f1 with the desired properties:
makeF <- function(){
x <- c(1,2,3)
f1 <- function() {
x^2
}
f1
}
f1 <- makeF()
f1() #returns 1 4 9
There is no x in the global scope but f1 still knows about the x in the environment that it was defined in.
In short: Your are expecting dynamic scoping but are a victim of R's lexical scoping:
dynamic scoping = the enclosing environment of a command is determined during run-time
lexical scoping = the enclosing environment of a command is determined at "compile time"
To understand the lookup path of your variable x in the current and parent environments try this code.
It shows that both functions do not share the environment in with x is defined in f2 so it can't never be found:
# list all parent environments of an environment to show the "search path"
parents <- function(env) {
while (TRUE) {
name <- environmentName(env)
txt <- if (nzchar(name)) name else format(env)
cat(txt, "\n")
if (txt == "R_EmptyEnv") break
env <- parent.env(env)
}
}
x <- c(1,2,3)
f1 <- function() {
print("f1:")
parents(environment())
x^2
}
f1() # works
# [1] "f1:"
# <environment: 0x4ebb8b8>
# R_GlobalEnv
# ...
rm(x)
f2 <- function() {
print("f2:")
parents(environment())
x <- c(1,2,3)
f1()
}
f2() # does not find "x"
# [1] "f2:"
# <environment: 0x47b2d18>
# R_GlobalEnv
# ...
# [1] "f1:"
# <environment: 0x4765828>
# R_GlobalEnv
# ...
Possible solutions:
Declare x in the global environment (bad programming style due to lack of encapsulation)
Use function parameters (this is what functions are made for)
Use a closure if x has always the same value for each call of f1 (not for beginners). See the other answer from #JohnColeman...
I strongly propose using 2. (add x as parameter - why do you want to avoid this?).

Passing variables through environments

I have the following two functions :
f1<-function(){
txt<-1234
f2(where="txt")
}
f2<-function(where){
foo<-eval(parse(text = where))*2
return(foo)
}
When calling f1(), I would expect it to return 2468. However
> f1()
Error in eval(expr, envir, enclos) : object 'txt' not found
I do not understand why, and specifically why f2 does not know txt. Of course it is not defined in its own environment, but it is defined in the caller environment (in f1), I thought everything defined within f1 should be visible to f2 ?
Of course, if in f1 I have
txt<<-1234
then
> f1()
[1] 2468
But I would rather avoid global assignments (in real code, I do not want to have stray global objects...)
So the question is, how can I make txt (defined in f1) visible to f2 ?
Thanks
(and in case you wonder, the real-life f2 is more complex, such that passing the name of a variable makes sense; in any case it is a function written by somebody else on which I have no control, so the solution should come from the f1 side).
1) The problem is really with f2, not with f1, so f2 should be fixed. One would normally define f2 to pass the environment explicitly. With this code f1 would work as is.
f2 <- function(where, envir = parent.frame()) {
eval(parse(text = where), envir = envir)*2` .
}
2) The following is less desirable; however, if we did not have control over f2 then we could do this in f1 (where now f2 is unchanged from the question):
f1 <- function() {
txt <- 1234
environment(f2) <- environment()
f2(where = "txt")
}
3) A third option is to define f2 within f1:
f1 <- function(){
f2 <- function(where) eval(parse(text = where))*2
txt <- 1234
f2(where = "txt")
}
f1()
Specify the envir argument in eval as parent.frame()
f2<-function(where){
foo<-eval(parse(text = where), envir= parent.frame())*2
return(foo)
}
f1()
#[1] 2468

R function which returns a function... and variable scope

I am learning about functions returning other functions. For example:
foo1 <- function()
{
bar1 <- function()
{
return(constant)
}
}
foo2 <- function()
{
constant <- 1
bar2 <- function()
{
return(constant)
}
}
Suppose, now, I declare functions f1 and f2 as follows:
constant <- 2
f1 <- foo1()
f2 <- foo2()
Then it appears they have the same function definition:
> f1
function()
{
return(constant)
}
<environment: 0x408f048>
> f2
function()
{
return(constant)
}
<environment: 0x4046d78>
>
BUT the two functions are different. For example:
> constant <- 2
> f1()
[1] 2
> f2()
[1] 1
My question: Why is it legal for two functions, with identical function definitions, to produce different results?
I understand that foo1 treats constant as a global variable and foo2 as a constant variable, but it is impossible to tell this from the function definition surely?
(I am probably missing something fundamental.)
Sure they're different, the environments are different. Try ls(environment(f1)) and then ls(environment(f2)) and then get('constant', environment (f1)) and same for f2
Scope in R
Lev's answer is correct. To describe in more detail. When you you call f1 or pass f1 around you also have a reference to the original lexical environment in which the function was defined.
#since R is interpreted.. the variable constant doesn't have to be defined in the lexical environment... this all gets checked and evaluated at runtime
foo1ReturnedThisFunction <- foo1()
#outputs "Error in foo1ReturnedThisFunction() : object 'constant' not found"
foo1ReturnedThisFunction()
#defined the variable constant in the lexical environment
constant <- 5
#outputs 5
foo1ReturnedThisFunction()
in foo2... there is a definition of the variable constant in the "closer" (not sure if this is the right term) lexical environment so it uses that and doesn't look for the variable constant in the "global" environment

Function with extra parameters from another function's input

This is a relatively simply problem but I'm stumped. I am programming in R, but I don't think this problem is restricted to R. Below I've tried to write some simple code demonstrating the problem:
f1 = function(x) {
return(a + x)
}
f2 = function(ftn) {
return(ftn(1))
}
f3 = function(a) {
return(f2(f1))
}
The Problem: If I call f3(2) [for example], f2(f1) is returned, and f2(f1) returns f1(a+1). But f1 does not recognize the value of 'a' that I put in f3, so the code doesn't work! Is there any way I can make it so that f1 recognizes the input into f3?
R uses lexical scope, not dynamic scope. Functions look up free variables (variables used but not defined within them) in the environment in which the function was defined. f1 was defined in the global environment so a is looked up in the global environment and there is no a there. We can force f1 to look up its free variables in the running instance of f3 like this:
f3 = function(a) {
environment(f1) <- environment()
return(f2(f1))
}
This temporarily creates a new f1 within f3 with the desired environment.
Another possibility if f1 is only needed within f3 is to define f1 there (rather than in the global environment):
f3 = function(a) {
f1 = function(x) {
return(a + x)
}
return(f2(f1))
}
By the way, the last expression evaluated in a running function is returned so this could be written:
f3 <- function(a) {
f1 <- function(x) a + x
f2(f1)
}

R specify function environment

I have a question about function environments in the R language.
I know that everytime a function is called in R, a new environment E
is created in which the function body is executed. The parent link of
E points to the environment in which the function was created.
My question: Is it possible to specify the environment E somehow, i.e., can one
provide a certain environment in which function execution should happen?
A function has an environment that can be changed from outside the function, but not inside the function itself. The environment is a property of the function and can be retrieved/set with environment(). A function has at most one environment, but you can make copies of that function with different environments.
Let's set up some environments with values for x.
x <- 0
a <- new.env(); a$x <- 5
b <- new.env(); b$x <- 10
and a function foo that uses x from the environment
foo <- function(a) {
a + x
}
foo(1)
# [1] 1
Now we can write a helper function that we can use to call a function with any environment.
with_env <- function(f, e=parent.frame()) {
stopifnot(is.function(f))
environment(f) <- e
f
}
This actually returns a new function with a different environment assigned (or it uses the calling environment if unspecified) and we can call that function by just passing parameters. Observe
with_env(foo, a)(1)
# [1] 6
with_env(foo, b)(1)
# [1] 11
foo(1)
# [1] 1
Here's another approach to the problem, taken directly from http://adv-r.had.co.nz/Functional-programming.html
Consider the code
new_counter <- function() {
i <- 0
function() {
i <<- i + 1
i
}
}
(Updated to improve accuracy)
The outer function creates an environment, which is saved as a variable. Calling this variable (a function) effectively calls the inner function, which updates the environment associated with the outer function. (I don't want to directly copy Wickham's entire section on this, but I strongly recommend that anyone interested read the section entitled "Mutable state". I suspect you could get fancier than this. For example, here's a modification with a reset option:
new_counter <- function() {
i <- 0
function(reset = FALSE) {
if(reset) i <<- 0
i <<- i + 1
i
}
}
counter_one <- new_counter()
counter_one()
counter_one()
counter_two <- new_counter()
counter_two()
counter_two()
counter_one(reset = TRUE)
I am not sure I completely track the goal of the question. But one can set the environment that a function executes in, modify the objects in that environment and then reference them from the global environment. Here is an illustrative example, but again I do not know if this answers the questioners question:
e <- new.env()
e$a <- TRUE
testFun <- function(){
print(a)
}
testFun()
Results in: Error in print(a) : object 'a' not found
testFun2 <- function(){
e$a <- !(a)
print(a)
}
environment(testFun2) <- e
testFun2()
Returns: FALSE
e$a
Returns: FALSE

Resources