问题描述
="a" = rlang::invoke()
已被弃用, purrr::invoke()
退役了.如今,以编程方式调用带有参数列表的函数的整洁方法是什么?
rlang::invoke()
is now soft-deprecated, purrr::invoke()
retired. These days, what is the tidy approach to programmatically calling a function with a list of arguments?
推荐答案
tldr; ;使用exec
代替invoke
;使用map2
加exec
代替invoke_map
.
tldr; Use exec
instead of invoke
; use map2
plus exec
instead of invoke_map
.
已退休的invoke
set.seed(2020)
invoke(rnorm, list(mean = 1, sd = 2), n = 10)
#[1] 1.7539442 1.6030967 -1.1960463 -1.2608118 -4.5930686 2.4411470
#[7] 2.8782420 0.5412445 4.5182627 1.2347336
使用exec
set.seed(2020)
exec(rnorm, n = 10, !!!list(mean = 1, sd = 2))
#[1] 1.7539442 1.6030967 -1.1960463 -1.2608118 -4.5930686 2.4411470
#[7] 2.8782420 0.5412445 4.5182627 1.2347336
invoke_map
的示例同样,您可以将map2
与exec
结合使用,而不是invoke_map
.以前,您将使用invoke_map
来使用带有不同参数集的函数
Example for invoke_map
Similarly, instead of invoke_map
you'd use map2
with exec
. Previously, you'd use invoke_map
to use a function with different sets of arguments
set.seed(2020)
invoke_map(rnorm, list(list(mean = 0, sd = 1), list(mean = 1, sd = 1)), n = 10)
# [[1]]
# [1] 0.3769721 0.3015484 -1.0980232 -1.1304059 -2.7965343 0.7205735
# [7] 0.9391210 -0.2293777 1.7591313 0.1173668
#
# [[2]]
# [1] 0.1468772 1.9092592 2.1963730 0.6284161 0.8767398 2.8000431
# [7] 2.7039959 -2.0387646 -1.2889749 1.0583035
现在,将map2
与exec
一起使用
set.seed(2020)
map2(
list(rnorm),
list(list(mean = 0, sd = 1), list(mean = 1, sd = 1)),
function(fn, args) exec(fn, n = 10, !!!args))
# [[1]]
# [1] 0.3769721 0.3015484 -1.0980232 -1.1304059 -2.7965343 0.7205735
# [7] 0.9391210 -0.2293777 1.7591313 0.1173668
#
# [[2]]
# [1] 0.1468772 1.9092592 2.1963730 0.6284161 0.8767398 2.8000431
# [7] 2.7039959 -2.0387646 -1.2889749 1.0583035
可悲的是,map2
加exec
语法不如invoke_map
简洁,但可能更规范.
Sadly, the map2
plus exec
syntax is not as concise as invoke_map
, but it is perhaps more canonical.
一些注释可以帮助避免在使用map2
加exec
时出现问题:
A few comments that may help avoid issues when using map2
plus exec
:
-
map2
的第一个参数必须为list
.因此map2(list(rnorm), ...)
将起作用.仅提供map2(rnorm, ...)
的功能就不会.这与invoke_map
不同,invoke_map
接受了功能的list
和功能本身. - 第二个参数必须是参数
list
s的list
.map2
将遍历顶级list
,然后在exec
中使用大爆炸运算符!!!
强制拼接函数参数的list
.
- The first argument of
map2
must be alist
. Somap2(list(rnorm), ...)
will work. Just providing the function asmap2(rnorm, ...)
will not. This is different toinvoke_map
, which accepted both alist
of functions and a function itself. - The second argument needs to be a
list
of argumentlist
s.map2
will iterate through the top-levellist
, and then use the big-bang operator!!!
insideexec
to force-splice thelist
of function arguments.
这篇关于现在已经不推荐使用invoke(),那有什么选择呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!