Passing variables through environments - r

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

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?).

R functions: passing arguments with ellipsis

I have a question regarding base R usage. It might be asked before, however I wasn't able to find solution to my problem.
I have a function that calls another function. Arguments to second function are passed using ellipsis (...). However, I get error message: object "OBJECT" not found.
f1 <- function(a, ...) {
print(a)
f2(...)
}
f2 <- function(...) {
print(b == TRUE)
print(runif(c))
}
f1(2, b = FALSE, c = 2)
Which gives me: Error in print(b == TRUE) : object 'b' not found.
I know that it is possible to get around this problem using args <- list(...) and then calling each argument separately, but I imagine that this gets complicated when having lots of arguments (not only two).
Question
How to pass arguments from f1 to f2 using ellipsis?
So the ellipses are used to save you specifying all the arguments of f2 in the arguments of f1. Though when you declare f2, you still have to treat it like a normal function, so specify the arguments b and c.
f1 <- function(a, ...) {
print(a)
f2(...)
}
# Treat f2 as a stand-alone function
f2 <- function(b, c) {
print(b == TRUE)
print(runif(c))
}
f1(2, b=FALSE, c=2)
[1] 2
[1] FALSE
[1] 0.351295 0.9384728

How can I manage environments to wrap functions and avoid environment issues?

Here are 4 functions which mimics a family of functions from basic to advanced.
f1 <- function(expr,envir) {
eval(expr,envir)
}
f2 <- function(expr) {
expr <- substitute(expr)
f1(expr,parent.frame())
}
f3 <- function(x) {
lapply(1:3, function(i) {
f2(x+i)
})
}
f4 <- function(...) {
f3(...)
}
f1 is the fundamental one, f2 calls f1 with an expression, f3 iteratively calls f2 with x defined in its body frame.
Calling f3 yields
> f3(1)
[[1]]
[1] 2
[[2]]
[1] 3
[[3]]
[1] 4
which has no problem because the x is evaluated correctly in parent.frame() of f2. However, if a wrapper function f4 is called, an error occurs:
> f4()
Error in eval(expr, envir, enclos) :
argument "x" is missing, with no default
I inspect the parent environments local to f2 in line and find that parent.frame(3) contains x: missing.
Is there a way or good practice to manage the environments so that I can wrap functions like f4 without worrying too much about the parent environment issues?

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)
}

`eval` using variable local to the function

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.

Resources