Skip to content

Instantly share code, notes, and snippets.

@tjmahr
Last active November 23, 2015 20:44
Show Gist options
  • Save tjmahr/eceb64d3bd60dc3787f7 to your computer and use it in GitHub Desktop.
Save tjmahr/eceb64d3bd60dc3787f7 to your computer and use it in GitHub Desktop.
# Function factory
make_adder <- function(x) {
function() x + 1
}
# Create list of functions with Map
funs <- Map(make_adder, 1:10)
unlist(Map(function(f) f(), funs))
# [1] 2 3 4 5 6 7 8 9 10 11
# Create list of functions with a for loop
funs2 <- list()
for (x in 1:10) {
funs2[[x]] <- make_adder(x)
}
unlist(Map(function(f) f(), funs2))
# [1] 11 11 11 11 11 11 11 11 11 11
# But we're cool if the one-off function is called on each loop
returns <- list()
for (x in 1:10) {
returns[[x]] <- make_adder(x)()
}
unlist(returns)
# [1] 2 3 4 5 6 7 8 9 10 11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment