Create new scope inside for loop in R

Viewed 67

When you create function in loop you got the same issue as in JavaScript you don't copy the value of the variable in for loop but use same reference, so at the end it always last value of the loop. I've thought that I can use same trick as in JavaScript and use IIFE, but this don't work:

x <- 1:10
y <- list()
for (e in x) {
   (function(e) {
     y <<- append(y, function() e)
   })(e)
}
y[[1]]()
# => 10

I've try to solve it using eval:

x <- 1:10
y <- list()
for (e in x) {
   eval(substitute({
     y <<- append(y, function() { e })
   }, list2env(list(e = e))))
}
y[[1]]()
# => 1
y[[9]]()
# => 9

but why this code don't work:

scope <- function(expr, ...) {
  eval(substitute(expr, list2env(list(...))))
}
x <- 1:10
y <- list()
for (e in x) {
   scope({
     y <<- append(y, function() { e })
   }, e = e)
}

got error:

Error in list2env(list(...)) : names(x) must be a character vector of the same length as x

Do you know how to create function scope or maybe other shorter/better way to create functions in loop in R?

I don't need this for any particular reason, just want to know how R works and how this should be done in R.

0 Answers
Related