Skip to content

Instantly share code, notes, and snippets.

@MrFlick
Created October 3, 2014 02:48
Show Gist options
  • Save MrFlick/3066a5973a4f7af91ed1 to your computer and use it in GitHub Desktop.
Save MrFlick/3066a5973a4f7af91ed1 to your computer and use it in GitHub Desktop.
capture.R: make sure variable is assigned in local enviroment
capture <- function(...) {
vars<-sapply(substitute(...()), deparse)
pf <- parent.frame()
Map(assign, vars, mget(Filter(exists, vars), envir=pf, inherits = TRUE), MoreArgs=list(envir=pf))
}
#capture will find a variable from an enclosing environment and will reassign it to the current (local) environment.
#Ignores variable names that do not exist
a <- c(3,7,11)
f <- list()
for(i in 1:3) {
f[[i]] <- local({capture(i, gobble); function(x) a[i]+x})
}
f[[1]](1)
# [1] 4
f[[3]](1)
# [1] 12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment