How to make purrr invoke_map work with closures

In order to create a function to deal with moving averages, I bumped into this problem. Using dplyr and purrr, I tried to generate a list of closures.

v <- 5
funs <- map(1:v, ~ . %>% lag(n = .x)  ) 

It occurs that, although funs[[1]](rnorm(100)) or funs[[2]](rnorm(100)) work, I didn't manage to make this line work:

invoke_map(funs, rnorm(100))

Why does this happen?

Upvotes: 3

Views: 82

Answers (1)

alistaire
alistaire

Reputation: 43354

invoke_map isn't sure how you want it to iterate. It's a very flexible function, which sometimes iterates across the functions, sometimes across the parameters, and sometimes across both. To make it explicit that you only want it to iterate across the functions, specify to which parameter rnorm(x) should go, though doing so is easier if you keep a traditional function structure instead of a functional sequence:

library(purrr)
set.seed(47)

funs <- map(1:5, ~partial(dplyr::lag, n = .x)) 

funs %>% 
    invoke_map(x = rnorm(10)) %>% 
    str(vec.len = 10)
#> List of 5
#>  $ : num [1:10] NA 1.9947 0.7111 0.1854 -0.2818 0.1088 -1.0857 -0.9855 0.0151 -0.252
#>  $ : num [1:10] NA NA 1.9947 0.7111 0.1854 -0.2818 0.1088 -1.0857 -0.9855 0.0151
#>  $ : num [1:10] NA NA NA 1.995 0.711 0.185 -0.282 0.109 -1.086 -0.985
#>  $ : num [1:10] NA NA NA NA 1.995 0.711 0.185 -0.282 0.109 -1.086
#>  $ : num [1:10] NA NA NA NA NA 1.995 0.711 0.185 -0.282 0.109

Upvotes: 3

Related Questions