为什么在purrr中的lambda函数中使用省略号...时必须将其包装在c()中 [英] why ellipsis ... have to be wrapped inside c() when used in lambda functions in purrr
问题描述
此问题可能称为此问题的第3部分.
我知道在 tidyverse
中使用的lambda函数中的参数,尤其是 purrr
函数中的参数写为-
I know that arguments in lambda functions when used in tidyverse
especially purrr
functions are written as -
-
.
只有1个参数时 -
.x
&.y
当有2 时 - 或
.. 1
,.. 2
,以此类推.2 个参数
.
when there is only 1 argument.x
&.y
when there are 2- OR
..1
,..2
so on when there are> 2
arguments
在链接的问题中,我了解到,如果必须同时传递所有参数,则可以使用省略号,即 ...
.
In the linked question, I learnt that if all the arguments have to be simultaneously passed we may use ellipsis i.e. ...
.
但是我的问题是,为什么这样的 ...
仅当包裹在 c()
中时才起作用,而当这样使用时却不起作用.在以下两种语法中,第二种有效,而第一种无效?
But my question, why such ...
work only when wrapped inside a c()
and doesn't work when used as such. In the below two syntaxes, second one works while first one doesn't?
#1 this doesn't work
pmap_df(iris[1:4], ~...)
Error in .f(Sepal.Length = .l[[1L]][[i]], Sepal.Width = .l[[2L]][[i]], :
'...' used in an incorrect context
#2 this however, works and returns the first argument after converting it to a tibble
pmap_df(iris[1:4], ~ c(...))
#see
identical(pmap_df(iris[1:4], ~c(...)), iris[1:4] %>% as_tibble())
[1] TRUE
有人可以解释吗?
推荐答案
The offical documentation has this to be said about the ellipsis:
The components of ‘...’ can be accessed in the usual pairlist manner from C code, but is not easily accessed as an object in interpreted code.
这可能是您问题的答案的一部分:省略号是一个不易访问的对象.
So that's possibly part of the answer to your question: The ellipsis is a not easily accessed object.
您可能必须进行野生动物园之旅,深入了解事物的C代码,以了解有关此内容的更多信息.
You would likely have to go on a safari trip down into the C-code of things to learn more about that.
现在,作为不易访问的对象, ...
当然不符合列表或向量的要求,而这正是pmap_df想要的.尽管从技术上讲,它可能可以.
Now being a not easily accessed object the ...
certainly doesn't qualify as a list or vector, which is what pmap_df wants. Although technically it probably could.
尽管看到如何使用〜
创建单行功能主体,但真正的原因可能是它本身并未首先考虑省略号.
However seeing how ~
is used to create one-liner function bodies, the real reason is probably that it itself does not consider the ellipsis in the first place.
考虑:
f <- function( ... ) {
~...
}
f(a=1,b=2) ## returns just `~...` , no trace of a and b in the formula's environment either.
现在考虑:〜........
.效果一样好.
Now consider: ~........
. Works just as fine.
〜
愉快地使用任意数量的点或其他字母数字字符,〜.......
或〜aaa ......例如bb ... cc ...
,有效地表明它并不关心查看省略号的正常方法,而只是将其视为名称的一部分.
~
happily takes any number of dots or other alfa num characters, ~.......
or ~aaa......bb...cc...
for example, effectively demonstrating it doesn't care about the otherwise normal way to look at the ellipsis and just treats them as part of a name.
这篇关于为什么在purrr中的lambda函数中使用省略号...时必须将其包装在c()中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!