Created
February 23, 2017 22:18
-
-
Save vsbuffalo/ffc82f6c7274fb4e2db85dadcd944077 to your computer and use it in GitHub Desktop.
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
library(purrr) | |
foo <- function(x) { | |
return(function(y) { | |
y + x | |
}) | |
} | |
args <- list(1, 2) | |
foos_map <- map(args, foo) | |
foos_lapply <- lapply(args, foo) | |
foos_map[[1]](1) | |
# returns 3 | |
foos_lapply[[1]](1) | |
# returns 2 | |
foos_map[[1]](2) | |
# returns 4 | |
foos_lapply[[1]](2) | |
# returns 3 |
This is related to metaprogramming. Here is an old blog post, discussing a similar issue of generating lots of functions having similar templates: Metaprogramming in R with an example: Beating lazy evaluation. One way to resolve this is to use substitute. It is a bit verbose though without using purrr
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've synthesized what everyone has said on this issue into a writeup that works through the problem in steps here: http://www.win-vector.com/blog/2017/02/iteration-and-closures-in-r/