Search code examples
rpurrrrlang

From purrr::invoke_map to rlang::exec (translate behavior)


I noticed that purrr::invoke_map() and his relatives were retired in favour of rlang::exec() used in conjunction with purrr::map, as documentation specified.

For some cases when you want to highlight different set of arguments to pass trough a function, purrr::invoke_map was very expresive, for example:

# create different settings of arguments in a list
args_list <- list(set1 = list(n = 5, mean = 0, sd = 1),
                  set2 = list(n = 5, mean = 10, sd = 2))

# pass each setting by the function
invoke_map(rnorm, args_list)

In the documentation you can find the following using exec + map2 to emulate above behavior:

 # Before:
 invoke_map(fns, list(args))
 invoke_map(fns, list(args1, args2))

 # After:
 map(fns, exec, !!!args)
 map2(fns, list(args1, args2), function(fn, args) exec(fn, !!!args))

How can we translate the formerly describe pattern using exec + map2?


Solution

  • Using map, when you have to apply the same function to args_list.

    library(purrr)
    args_list <- list(set1 = list(n = 5, mean = 0, sd = 1),
                      set2 = list(n = 5, mean = 10, sd = 2))
    
    map(args_list, ~exec(rnorm, !!!.x))
    

    Using map2 when you want to apply different functions

    args_list <- list(set1 = list(n = 5, mean = 0, sd = 1),
                      set2 = list(n = 3, min = 1, max = 2))
    
    map2(args_list, list(rnorm, runif), ~exec(.y, !!!.x))