minem
minem

Reputation: 3650

execution of a function with a specific environment variable

I apparently do not understand how to use environments, so maybe someone can help me. I want to eval those function in sapply, so they use k = 1.

fList <- list(function(x) k + 3, function(x) k + 4)
k <- 3
t <- sapply(1:2,
            function(x) {
               f <- fList[[x]]
               evalq(s <- f(1), list(k = 1))
               evalq(s <<- f(1), list(k = 1))
               s
             })
t

Upvotes: 1

Views: 44

Answers (1)

MrFlick
MrFlick

Reputation: 206207

Functions in R use lexical scoping. This means they look for variable values in the environment where they were defined, not where they were run. You can change the environment of a function however. This is possible (not not necessarily recommended)

fList <- list(function(x) k + 3, function(x) k + 4)
k <- 3
t <- sapply(1:2,
            function(x) {
              f <- fList[[x]]
              env <- new.env(parent=baseenv())
              env$k <- 1
              environment(f) <- env
              s<-f(1)
              s <<- f(1)
              s
            })
t
# [1] 4 5

You could also use expressions rather than functions

eList <- expression( k + 3, k + 4)
k <- 3
t <- sapply(1:2,
            function(x) {
              e <- eList[[x]]
              s <- eval(e, list(k = 1))
              s <<- eval(e, list(k = 1))
              s
            })
t

But it would probably be better to not leave free variables in your function at all and explicitly pass parameters or an environment to that function.

Upvotes: 2

Related Questions