Martijn Tennekes
Martijn Tennekes

Reputation: 2051

How to access variables from higher environments

f <- function(x, y, z) {
    lapply(as.list(match.call()[-1]), eval)
}

f(x=2, z=3)

The output is as expected:

$x
[1] 2

$z
[1] 3

However, when this function is wrapped into another one, it fails.

g <- function(a) {
    f(x=a, z= 3)
}

g(2)

The error message:

Error in FUN(X[[i]], ...) : object 'a' not found

Apparently, the eval function only looks in the parent environment, not in higher environments. In debug mode, it works as expected:

> g <- function(a) {
+   browser()
+   f(x=a, z= 3)
+ }
> g(2)
Called from: g(2)
Browse[1]> a
[1] 2

Upvotes: 2

Views: 43

Answers (1)

TimSalabim
TimSalabim

Reputation: 5844

This is taken from ?eval examples:

f <- function(x, y, z) {
  e1 <- parent.frame()
  lapply(as.list(match.call()[-1]), eval, envir = e1)
}

f(x=2, z=3)

g <- function(a) {
  f(x=a, z= 3)
}

g(5)

It seems you need to specifically define the parent environment.

Upvotes: 2

Related Questions