Created
October 3, 2014 02:48
-
-
Save MrFlick/3066a5973a4f7af91ed1 to your computer and use it in GitHub Desktop.
capture.R: make sure variable is assigned in local enviroment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
capture <- function(...) { | |
vars<-sapply(substitute(...()), deparse) | |
pf <- parent.frame() | |
Map(assign, vars, mget(Filter(exists, vars), envir=pf, inherits = TRUE), MoreArgs=list(envir=pf)) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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