Search code examples
rlistfunctionauto-generate

Make list of functions with lapply


Is there any way to make the following list of functions using lapply? Below, I make a list named "long" the long way. I would like to simplify the code using lapply (or a for loop) but neither seems to work. Thank you.

#This works as expected
long <- list(function(x) x <- within(x, DATE <- as.Date("2013-01-01")),
             function(x) x <- within(x, DATE <- as.Date("2014-01-01")),
             function(x) x <- within(x, DATE <- as.Date("2015-01-01")))

#This does not work
long <- lapply(2013:2015, function(i) x <- within(x, DATE <- as.Date(paste(i, "01", "01", sep = "-"))))

#This does not work
for (i in 2013:2015) long <- list(function(x) x <- within(x, DATE <- as.Date(paste(i, "01", "01", sep = "-"))))

Solution

  • Maybe the simplest method is to add another function.

    long <- lapply(2013:2015,
                  function(i) function(x) {
                               x <- within(x, DATE <- as.Date(paste(i, "01", "01", sep = "-")))})
    

    Check that the elements are functions

    typeof(long[[1]])
    [1] "closure"
    

    Test it

    # empty list, x
    x <- list()
    x <- long[[1]](x)
    x
    $DATE
    [1] "2013-01-01"
    

    As @Roland mentions in the comments, it would be safer to force the evaluation of the i argument.

    long <- lapply(2013:2015, function(i) {
                                force(i);
                                function(x) x <- within(x,
                                                DATE <- as.Date(paste(i, "01", "01", sep = "-")))
                               })