Last active
November 23, 2015 20:44
-
-
Save tjmahr/eceb64d3bd60dc3787f7 to your computer and use it in GitHub Desktop.
This file contains 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
# 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