从purrr :: invoke_map到rlang :: exec(转换行为)

问题描述 投票:0回答:1

[我注意到purrr::invoke_map()和他的亲戚已退休,而赞成rlang::exec()purrr::mapas documentation specified结合使用。

[在某些情况下,当您想突出显示一组不同的参数以通过函数时,purrr::invoke_map表示得非常好,例如:

# 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)

在文档中,您可以使用exec + map2模仿以下行为找到以下内容:

 # 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))

我们如何使用exec + map2翻译以前描述的模式?

r purrr rlang
1个回答
0
投票

使用map,当您必须将相同功能应用于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))

想要应用其他功能时使用map2

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))
© www.soinside.com 2019 - 2024. All rights reserved.