在 R 中解压省略号的参数列表
我对某些函数中省略号(...
)的使用感到困惑,即如何将包含参数的对象作为单个参数传递。
在Python 中,它被称为“解包参数列表”,例如,
>>> range(3, 6) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args) # call with arguments unpacked from a list
[3, 4, 5]
在R 中,您有使用省略号的函数file.path(...)
。我希望有这种行为:
> args <- c('baz', 'foob')
> file.path('/foo/bar/', args)
[1] 'foo/bar/baz/foob'
相反,我得到了
[1] 'foo/bar/baz' 'foo/bar/foob'
args 的元素没有“解压”并同时求值的位置。 R 是否有相当于 Python 的 *arg
?
I am confused by the use of the ellipsis (...
) in some functions, i.e. how to pass an object containing the arguments as a single argument.
In Python it is called "unpacking argument lists", e.g.
>>> range(3, 6) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args) # call with arguments unpacked from a list
[3, 4, 5]
In R for instance you have the function file.path(...)
that uses an ellipsis. I would like to have this behaviour:
> args <- c('baz', 'foob')
> file.path('/foo/bar/', args)
[1] 'foo/bar/baz/foob'
Instead, I get
[1] 'foo/bar/baz' 'foo/bar/foob'
where the elements of args
are not "unpacked" and evaluated at the same time. Is there a R equivalent to Pythons *arg
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
语法并不那么漂亮,但这确实有效:
do.call
接受两个参数:一个函数和调用该函数的参数列表。The syntax is not as beautiful, but this does the trick:
do.call
takes two arguments: a function and a list of arguments to call that function with.您可以通过在函数内调用
list(...)
从省略号中提取信息。在这种情况下,省略号中的信息被打包为列表对象。例如:您可以通过调用
do.call
从矢量化函数(如file.path
)实现所需的行为,有时与包装器一起使用会更简单splat
(在plyr
包中)You can extract information from the ellipsis by calling
list(...)
inside the function. In this case, the info in the ellipsis is packaged as a list object. For example:You can achieve the desired behaviour from vectorised functions like
file.path
with a call todo.call
, which is sometimes simpler to use with the wrappersplat
(in theplyr
package)我花了一段时间才找到它,但是
purrr
包有一个等效的到plyr::splat
:它被称为lift_dl
。名称中的“dl”代表“dots to list”,因为它是一系列
lift_xy
函数的一部分,可用于将函数的域从一种输入“提升”为另一种,这些“种类”是列表、向量和“点”。由于
lift_dl
可能是其中最有用的,因此为其提供了一个简单的lift
别名。要重用上面的示例:
更新
从 purrr 1.0.0 开始,
lift_*
函数系列已被弃用。展望未来,应该使用
rlang::inject
通过!!!
运算符启用拼接:It took me a while to find it, but the
purrr
package has an equivalent toplyr::splat
: it's calledlift_dl
.The "dl" in the name stands for "dots to list", as it's part of a series of
lift_xy
functions that can be used to "lift" the domain of a function from one kind of input to another kind, these "kinds" being lists, vectors and "dots".Since
lift_dl
is probably the most useful of those, there is a simplelift
alias provided for it.To reuse the above example:
Update
As of purrr 1.0.0, the
lift_*
family of functions is deprecated.Moving forward, one should instead use
rlang::inject
to enable splicing via the!!!
operator: