在调用使用 tidyselect 的函数时指定点参数而不需要指定前面的参数
Specify the dots argument when calling a tidyselect-using function without needing to specify the preceding arguments
这是我在使用 ...
参数和 tidyselect
到 select 变量的包中的函数的简化版本:
# this toy function just selects the ... variables
foo <- function(dat = mtcars, ...){
expr <- rlang::expr(c(...))
cols_to_select <- tidyselect::eval_select(expr, data = dat)
dplyr::select(dat, all_of(cols_to_select))
}
这个有效:foo(mtcars, cyl)
但我的实际函数在 ...
参数之前有更多的前置参数,所有参数都具有默认值。在我使用这些默认值调用我的函数并将值传递给 ...
的情况下,将它们全部键入是很乏味的。
这就是我想要的 - 假设 dat = mtcars
- 但它不起作用:
foo(... = cyl)
Error: Names must not be of the form ...
or ..j
.
我可以修改函数或调用以允许直接指定 ...
吗?
将具有默认值的参数放在 点之后通常是个好主意™:
f <- function( ..., dat=mtcars )
dplyr::select( dat, ... )
f(cyl) # Works
f(dat=iris, Species) # Also works
如果您的 API 不允许您在点之后放置命名的默认参数,这里有另一种选择。请注意,您不必明确指定具有默认值的命名参数。你可以简单地离开他们 "missing":
foo(, cyl) # Same as foo( dat=mtcars, cyl )
如果您有很多默认参数,并且不想在调用中一直使用逗号,则可以使用 purrr::partial()
将此模式捕获到一个独立的函数中:
foo2 <- purrr::partial(foo, ,) # Effectively partial(foo, dat=mtcars)
foo2(cyl) # Works
如果仍然需要输入比您喜欢的更多的逗号,您可以再添加一个步骤:
foo3 <- purrr::partial( foo, !!!purrr::keep(formals(foo), nzchar) )
foo3(cyl, mpg) # Also works
这是我在使用 ...
参数和 tidyselect
到 select 变量的包中的函数的简化版本:
# this toy function just selects the ... variables
foo <- function(dat = mtcars, ...){
expr <- rlang::expr(c(...))
cols_to_select <- tidyselect::eval_select(expr, data = dat)
dplyr::select(dat, all_of(cols_to_select))
}
这个有效:foo(mtcars, cyl)
但我的实际函数在 ...
参数之前有更多的前置参数,所有参数都具有默认值。在我使用这些默认值调用我的函数并将值传递给 ...
的情况下,将它们全部键入是很乏味的。
这就是我想要的 - 假设 dat = mtcars
- 但它不起作用:
foo(... = cyl)
Error: Names must not be of the form
...
or..j
.
我可以修改函数或调用以允许直接指定 ...
吗?
将具有默认值的参数放在 点之后通常是个好主意™:
f <- function( ..., dat=mtcars )
dplyr::select( dat, ... )
f(cyl) # Works
f(dat=iris, Species) # Also works
如果您的 API 不允许您在点之后放置命名的默认参数,这里有另一种选择。请注意,您不必明确指定具有默认值的命名参数。你可以简单地离开他们 "missing":
foo(, cyl) # Same as foo( dat=mtcars, cyl )
如果您有很多默认参数,并且不想在调用中一直使用逗号,则可以使用 purrr::partial()
将此模式捕获到一个独立的函数中:
foo2 <- purrr::partial(foo, ,) # Effectively partial(foo, dat=mtcars)
foo2(cyl) # Works
如果仍然需要输入比您喜欢的更多的逗号,您可以再添加一个步骤:
foo3 <- purrr::partial( foo, !!!purrr::keep(formals(foo), nzchar) )
foo3(cyl, mpg) # Also works